以下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 theexec()
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'slastIndex
property (test()
will also advance thelastIndex
property).
重要说明:引用部分第一行的第一部分很重要。 如果您的正则表达式使用
“g”标志
。 仅当 RegEx 具有 g
标志时,您才会出现此行为。
关于javascript - Eloquent Javascript 在 RegExp 匹配上循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29591848/