我正在通过能言善辩JavaScript的正则表达式章(http://eloquentjavascript.net/09_regexp.html)我的方式和我卡在自己的一个例子:Eloquent Javascript正则表达式示例:为什么Exec返回两项数组?
var input = "A string with 3 numbers in it... 42 and 88.";
var number = /\b(\d+)\b/g;
var match;
while (match = number.exec(input))
console.log("Found", match[1], "at", match.index);
// → Found 3 at 14
// Found 42 at 33
// Found 88 at 40
正则表达式本身很简单,但我认为这是奇怪的比赛[1 ]给出了匹配的正确字符串。所以我把它改成了match[0]
,跑起来,得到了完全一样的结果。
所以我改变了计划打印出match
为好,果然,我得到了相同的值数组中的索引0和1:
var input = "A string with 3 numbers in it... 42 and 88.";
var number = /\b(\d+)\b/g;
var match;
while (match = number.exec(input)){
console.log("Found", match[1], "at", match.index);
console.log(match);
}
// → Found 3 at 14
// ["3", "3"]
// Found 42 at 33
// ["42", "42"]
// Found 88 at 40
// ["88", "88"]
我不知道为什么我得到这个结果,我没有看到将匹配的文本两次推送到同一个数组的目的。根据他们以前的例子,它更没有意义:
var digit = /\d/g;
console.log(digit.exec("here it is: 1"));
// → ["1"]
console.log(digit.exec("and now: 1"));
// → null
这是怎么回事?为什么.exec有时会在数组中返回一次值,而在其他时间则会在数组中返回两次?
由于捕获组。 –
实际上,'RegExp#exec'与'没有全局修饰符的正则表达式一起使用的'String#match'是做同样的事情。请参阅http://stackoverflow.com/questions/9002771/match-returns-array-with-two-matches-when-i-expect-one-match –