简体   繁体   English

Eloquent Javascript循环使用RegExp匹配

[英]Eloquent Javascript Looping over RegExp Matches

The following example is a bit confusing to me: 以下示例对我来说有点混乱:

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);
}

Specifically, I don't understand how this has a "looping" effect. 具体来说,我不明白这是如何产生“循环”效应的。 How does it run through all the matches within one string if it keeps calling match[1] . 如果它一直调用match[1] ,它如何在一个字符串中运行所有匹配。 Is there some kind of side effect with exec that I am unaware of? 我不知道有没有某种副作用?

Edit: I still would like an answer to how match[1] is working. 编辑:我仍然希望得到match[1]的工作方式的答案。 How does match[1] produce any answer? match[1]如何产生任何答案? When I test this type of thing myself, I get undefined , look 当我自己测试这种类型的东西时,我得到了undefined ,看起来

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

Whats going on here? 这里发生了什么? Wouldn't it be y[0], or in the case above, match[0]? 不是y [0],或者在上面的情况下匹配[0]? Like: 喜欢:

> y[0]
'5'

The RegExp object remembers the last matched position with lastIndex property. RegExp对象记住lastIndex属性的最后匹配位置。

Quoting MDN Documentation , 引用MDN文档

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. 如果正则表达式使用"g"标志,则可以多次使用exec()方法在同一个字符串中查找连续匹配。 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). 执行此操作时, 搜索从正则表达式的lastIndex属性指定的str的子字符串开始test()也将提前执行lastIndex属性)。

Important Note: The first part of the first line of the quoted section is important. 重要说明:引用部分第一行的第一部分很重要。 If your regular expression uses the "g" flag . If your regular expression uses the “g” flag Only if the RegEx has g flag you will get this behavior. 只有RegEx有g标志,你才会得到这种行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM