没有全局标志的正则表达式分组或运算符匹配策略

Regex grouped OR operator matching strategy without global flag

代码片段

'a b'.match(/a|b/ig)

returns

["a", "b"]

这完全符合预期,因为我们正在使用 'a' 或 'b' 搜索子字符串 但为什么

'a b'.match(/(a|b)/i)

return

["a", "a"]

作为输出,a如何匹配两次? 'a b'.match(/a|b/i)

不应该是["a"]

'a b'.match(/(a|b)/i) 中,您的第一个示例中有一个不退出的捕获组。结果数组包含完全匹配的值(即 a)和第一个捕获组的值(即 a)。

这就是为什么你 ["a", "a"]

这里的答案在documentation:

If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

因此 'a b'.match(/(a|b)/i)/(a|b)/i.exec('a b') 相同,后者将 return 匹配的字符串和捕获的组,因此,一个捕获组,一个额外的数组条目。

另一方面:

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. If there were no matches, the method returns null.