JS正则表达式没有返回所有匹配的组

时间:2015-09-18 12:59:50

标签: javascript regex

我的字符串如下:

var data = "Validation failed: Attachments document 01april2015_-_Copy.csv has contents that are not what they are reported to be, Attachments document 01april2015.csv has contents that are not what they are reported to be"

我的正则表达式:

var regex = /Validation failed:(?:(?:,)* Attachments document ([^,]*) has contents that are not what they are reported to be)+/;

结果:

data.match(regex)
  

[“验证失败:附件文件01april2015 _-_ Copy.csv的内容不是他们报告的内容,附件文件01april2015.csv的内容不是他们所报告的内容”,“01april2015.csv” ]

data.match(regex).length == 2
  

预期结果:

data.match(regex)
  

[“验证失败:附件文件01april2015 _- Copy.csv的内容不是他们报告的内容,附件文件01april2015.csv的内容不是他们报告的内容”,“01april2015 -_ Copy.csv“,”01april2015.csv“]

data.match(regex).length == 3
  

我无法理解为什么在匹配后没有返回第一个文件名(01april2015_-_Copy.csv)。任何形式的解释都将深表感谢。

1 个答案:

答案 0 :(得分:4)

在JS中,没有C#中的Captures集合,因此,我建议使用带有g选项的缩写正则表达式,并将其与exec一起使用,以免丢失捕获的文本:

var re = /Attachments document ([^,]*) has contents that are not what they are reported to be/g; 
var str = 'Validation failed: Attachments document 01april2015_-_Copy.csv has contents that are not what they are reported to be, Attachments document 01april2015.csv has contents that are not what they are reported to be';
var m;
var arr = [str];
while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    arr.push(m[1]);
}
console.log(arr);

请注意,可以使用与所需子字符串匹配的最短模式来查找多个匹配项。我们无法使用String#match,因为:

  

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

     

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

使用/g

查看RegExp#exec行为
  

如果正则表达式使用"g"标志,则可以多次使用exec()方法在同一字符串中查找连续匹配。

     

如果匹配成功,exec()方法将返回一个数组并更新正则表达式对象的属性。 返回的数组匹配的文本作为第一项,然后匹配包含所捕获文本的每个捕获括号的一个项目