[英]Javascript Replace function not working with regex
我有以下字符串:
@[A:B:C].[X:Y:Z].[P:Q:R] 1.C.3.s @[1:2:3].[2:0:0].[5dsh:cxcv:wew]
我想從子字符串中提取以下格式的子字符串:
@[anything here].[anything here].[anything here]
在上述情況下,輸出子字符串應為:
@[A:B:C].[X:Y:Z].[P:Q:R]
@[1:2:3].[2:0:0].[5dsh:cxcv:wew]
我有匹配這些子字符串的正則表達式:
(@\w+|@(?:\[[^\]]+\]\.?)+)
為了測試此正則表達式,我在此提琴中用$
替換了這些子字符串: http : //jsfiddle.net/vfe50z0o/
正則表達式沒有問題,因為它可以在此Regex101演示中使用: https ://regex101.com/r/aH9nK5/1
但是在JSFiddle上它不起作用。
這是JavaScript代碼:
function myFunction() {
var re = /(@\w+|@(?:\[[^\]]+\]\.?)+)/;
var str = 'wewe@[s].[s].[s]xvcv';
var subst = '$';
var result = str.replace(re, subst);
alert(result);
}
您可以使用以下代碼獲取匹配項:
var re = /(@\w*(?:\[[^\]]+\]\.?)+)/g;
var str = '@[A:B:C].[X:Y:Z].[P:Q:R] 1.C.3.s @[1:2:3].[2:0:0].[5dsh:cxcv:wew]';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex)
re.lastIndex++;
console.log(m[1]);
}
輸出:
@[A:B:C].[X:Y:Z].[P:Q:R]
@[1:2:3].[2:0:0].[5dsh:cxcv:wew]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.