javascript - Eloquent Javascript 在 RegExp 匹配上循环

标签 javascript regex

以下example对我来说有点困惑:

var text = "A string with 3 numbers in it ... 42 and 88.";
var number = /\b(\d+)\b/g;
var match;
while (match = number.exec(text)){
    console.log("Found", match[1], "at", match.index);
}

具体来说,我不明白这是如何产生“循环”效果的。如果它一直调用 match[1],它如何遍历一个字符串中的所有匹配项。 exec 是否有某种我不知道的副作用?

编辑: 我仍然想知道 match[1] 是如何工作的。 match[1] 如何产生任何答案?当我自己测试这种类型的东西时,我得到 undefined,看

> var y = /\d+/g.exec('5')
undefined
> y
[ '5', index: 0, input: '5' ]
> y[1]
undefined

这是怎么回事?难道不是 y[0],或者在上面的例子中是 match[0]?喜欢:

> y[0]
'5'

最佳答案

RegExp 对象会记住最后一个与 lastIndex 匹配的位置属性(property)。

引用 MDN Documentation ,

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property).

重要说明:引用部分第一行的第一部分很重要。 如果您的正则表达式使用“g”标志仅当 RegEx 具有 g 标志时,您才会出现此行为。

关于javascript - Eloquent Javascript 在 RegExp 匹配上循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29591848/

相关文章:

javascript - 正则表达式将括号内的所有双引号替换为单引号

regex - 将正则表达式与 `rename` 中的 `util-linux` 版本一起使用

javascript - 检查两个日期是否具有相同的日期信息

javascript - 我可以在没有访问 token 的情况下获取 Instagram 照片的所有评论吗?

javascript - 删除两个重复的项目 javascript 数组

javascript - 如何将 "20hc+2a+2hc+9op"之类的字符串表达式减少到 "22hc+2a+9op"

regex - 强制正则表达式两边都用引号括起来,或者根本不括起来,而不重复表达式

python - 如何使用正则表达式在句子内搜索 - 不区分大小写

javascript - 我想调用javascript函数,当选择选项(它基于for循环)仅被选择一次时

javascript - 如何根据html页面更改英雄形象?