javascript - js正则表达式差异

标签 javascript regex brackets

我有一个 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/

相关文章:

c# - 检查字符串是否包含 ip 地址

javascript - div 中无法选择的文本到可选择的传单

regex - Sed 匹配数字后跟字符串并返回数字

javascript - 如何在 Angular js中的现有数组中添加新键?

php - 检查 PHP 引荐来源网址

Javascript 点表示法与括号表示法

java - 正则表达式分配不正确

Java eclipse 突出显示缺少的括号

javascript - 如何屏蔽黑莓浏览器上的输入

javascript - 如何通过隐藏/显示具有动态属性的 div 进行过滤?