Javascript全局匹配捕获组 [英] Javascript global match with capturing groups

查看:68
本文介绍了Javascript全局匹配捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我为什么在使用 g 标志时,第二个片段是否会捕获'群组'?

Can anyone tells me why does't the second snippet catchs the 'groups' when use g flag ?

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

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 docs


如果正则表达式不包含g标志,则返回与RegExp.exec()相同的结果。返回的Array有一个额外的input属性,它包含已解析的原始字符串。此外,它有一个index属性,表示字符串中匹配的从零开始的索引。

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.

如果正则表达式包含g标志,则该方法返回包含所有匹配的子字符串而不是匹配对象的数组。捕获的组不会被退回。如果没有匹配项,则该方法返回null。

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.








如果要获取捕获组并设置全局标志,则需要使用 RegExp.exec()

var myRe = /(\d)(\d)/g;
var str = '12 34';
var myArray;
while (myArray = myRe.exec(str)) {
  console.log(myArray);
}

这篇关于Javascript全局匹配捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆