js正则表达式差异

js regex discrepancy

我有一个 JS 正则表达式匹配,似乎包含错误的括号。我在 Regex101 对其进行了测试,它似乎在那里正常工作,但是当我 运行 它时,我收到此警报响应:

[#],[Type,' '],[Problem w/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"]