为什么带括号的 string.match(/(regexp)/);
返回匹配两次?
例如:"abcdef".match(/(cd)/);
返回 cd
的两个实例:["cd","cd"]
我查看了 MDN documentation .它没有说明多次返回匹配项。
我什至查看了 ECMA docs .
通过获取 [1]
索引 string.match()
有一个解决方法,但我在文档中找不到解释。
最佳答案
让我们按照 RegExp.match 上的文档进行操作
If the regular expression does not include the g flag, returns the same result as RegExp.exec(str).
好的,转到 RegExp.exec
If the match succeeds, the exec method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
关于javascript - 为什么带括号的 string.match(/(regexp)/) 返回匹配两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057031/