我正在阅读 Eloquent Javascript 的 RegEx 章节 ( http://eloquentjavascript.net/09_regexp.html ),但我陷入了其中的一个示例:
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
正则表达式本身很简单,但我认为 match[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 有时只在数组中返回一次值,而有时在数组中返回两次值?
最佳答案
.exec()
将始终返回匹配的字符串作为数组中的初始元素,然后将任何匹配的组作为其余的索引返回。
示例:
var regex1 = /abc/;
var regex2 = /a(b)c/;
var string = 'We always match "abc".';
console.log(regex1.exec(string));
console.log(regex2.exec(string));
因此,两种模式都匹配相同的内容,但由于在第二个示例中存在组捕获 b
,因此它将由 exec()
返回。
关于javascript - Eloquent Javascript 正则表达式示例 : Why Is Exec Returning A Two-Item Array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39649501/