1 回答

TA贡献1785条经验 获得超4个赞
这实际上是预期的行为,信不信由你。exec()JavaScript regex 上的方法是有状态的,旨在成为人们在循环中调用的东西。每次后续执行都将返回字符串中的下一个匹配项,直到找不到更多匹配项为止,此时null将返回。
为了在第一个示例中突出显示这一点,让我们快速简化一下代码并显示每个变量中的值。
let testRegex = /yolo .+ .+/gu;
let test = [
"yolo 2 abc",
"yolo 2 abc"
]
这会导致您的调用testRegex.exec看起来像以下内容:
testRegex.exec("yolo 2 abc") // => Array ["yolo 2 abc"]
testRegex.exec("yolo 2 abc") // => null
您可以在此处找到有关此内容的官方文档,其中说明:
如果您的正则表达式使用“g”标志,您可以exec()多次使用该方法来查找同一字符串中的连续匹配项。当您这样做时,搜索从str正则表达式的lastIndex属性指定的子字符串开始(test()也将推进该lastIndex属性)。请注意,lastIndex搜索不同的字符串时不会重置该属性,它将从现有的lastIndex.
您提供的第二个示例没有遇到此问题的原因是该match()函数在lastIndex内部将属性重置为 0,重置搜索位置并导致第二次调用exec()从正则表达式的开头进行搜索。
回到你原来的例子,你可以修改它如下,你会看到你期望的行为:
var testRegex = /yolo .+ .+/gu;
let test = `yolo 2 abc
yolo 2 abc`;
test = test.split('\n');
for (let t=0; t < test.length; t++)
{
console.log(test[t], testRegex.exec(test[t]));
testRegex.lastIndex = 0;
}
添加回答
举报