我有一个 JS 正则表达式匹配,它似乎错误地包含了括号。我在 Regex101 测试了它它似乎在那里正常工作但是当我运行它时我得到这个警报响应:
[#],[Type,' '],[ICD 问题],['- ',Assessment],[' : ',Comment],[LF],[LF]
var temp = "[#]. [Type,' '][Problem w/ICD]['- ',Assessment][' : ',Comment][LF][LF]";
var rep = temp.match(/\[(.*?)\]/g);
alert(rep);
为什么括号在捕获组之外时包含在内?
最佳答案
包含括号是因为在使用 string#match
时和带有 /g
修饰符的正则表达式,您将丢失捕获组。
If the regular expression includes the
g
flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned.
您需要在循环中使用 RegExp#exec()
,并通过索引 1 访问第一个捕获组。
var re = /\[(.*?)\]/g;
var str = '[#]. [Type,\' \'][Problem w/ICD][\'- \',Assessment][\' : \',Comment][LF][LF]';
var m;
var res = [];
while ((m = re.exec(str)) !== null) {
res.push(m[1]);
}
console.log(res);
结果:
["#", "Type,' '", "Problem w/ICD", "'- ',Assessment", "' : ',Comment", "LF", "LF"]
关于javascript - js正则表达式差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113423/