Javascript正则异常匹配字符串在Chrome和Firefox每两次尝试一次



我在javascript中有以下正则表达式:

var the_regexp = /^/([!/]*)/?(w*)??([=|w]*)/?$/gi

在Firefox和Chrome控制台,它每两次尝试找到字符串"/d"的匹配。

>the_regexp
/^/([!/]*)/?(w*)??([=|w]*)/?$/gi
>the_regexp.exec("/d")
null
>the_regexp.exec("/d")
["/d", "", "d", ""]
>the_regexp.exec("/d")
null
>the_regexp.exec("/d")
["/d", "", "d", ""]
谁能解释一下这种行为?

MDN Docs:

如果你的正则表达式使用"g"标志,你可以使用exec方法多次查找同一字符串中的连续匹配项。指定的str的子字符串开始搜索正则表达式的lastIndex属性

所以当你的正则表达式有一个g标志,并且你使用了一次exec方法,下一次你执行它时,它将在第一次匹配之后搜索匹配。在这种情况下,没有:exec将返回null, lastIndex属性将被重置。

例如:

var str = "abcdef";
//         ^ starting index for search is here
var regex = /ab/g;
regex.exec(str);
// str: "abcdef"
//         ^ starting index for search is now here
regex.exec(str);
// no match found from starting index, return null and reset
// str: "abcdef"
//       ^ starting index reset

您可能想要从Regex中删除g标志,这取决于您想要实现的目标。此外,那些空的捕获组看起来有点多余。

编辑:看起来Reanimation赢了我;)

相关内容

最新更新