关于正则表达式:与捕获组的Javascript全局匹配

Javascript global match with capturing groups

本问题已经有最佳答案,请猛点这里访问。

有人能告诉我为什么第二个片段在使用g标志时不捕获"groups"?

1
2
 "123".match(/(\d{1})(\d{1})/)    // returns  ["12","1","2"]
 "123".match(/(\d{1})(\d{1})/g)   // returns ["12"]   (where's 1 and 2 ?)

1
2
3
console.log("123".match(/(\d{1})(\d{1})/))    // returns  ["12","1","2"]

console.log("123".match(/(\d{1})(\d{1})/g))   // returns ["12"]   (where's 1 and 2 ?)


根据MDN文档:

If the regular expression does not include the g flag, returns the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.

If you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() instead.

1
2
3
4
5
6
var myRe = /(\d)(\d)/g;
var str = '12 34';
var myArray;
while (myArray = myRe.exec(str)) {
  console.log(myArray);
}