2016-09-22 26 views
0

我正在通过能言善辩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有时会在数组中返回一次值,而在其他时间则会在数组中返回两次?

+1

由于捕获组。 –

+0

实际上,'RegExp#exec'与'没有全局修饰符的正则表达式一起使用的'String#match'是做同样的事情。请参阅http://stackoverflow.com/questions/9002771/match-returns-array-with-two-matches-when-i-expect-one-match –

回答

1

.exec()总是返回匹配的字符串作为数组中的初始元素,然后返回任何匹配的组作为剩余的indeces。

实施例:

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()返回。

+0

我现在看到了。我只是不完全理解返回的内容。非常感谢你! – sadq3377

相关问题