gpt4 book ai didi

javascript - JS 正则表达式不返回所有匹配的组

转载 作者:行者123 更新时间:2023-11-30 08:34:44 24 4
gpt4 key购买 nike

我的字符串如下:

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)

["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", "01april2015.csv"]

data.match(regex).length == 2

true

预期结果:

data.match(regex)

["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", "01april2015-_Copy.csv", "01april2015.csv"]

data.match(regex).length == 3

true

我无法理解为什么它在匹配后不返回第一个文件名(01april2015_-_Copy.csv)。任何形式的解释将不胜感激。

最佳答案

在JS中,没有Captures与 C# 中的集合一样,因此,我建议使用带有 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 因为:

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 you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() instead.

参见 RegExp#exec /g 的行为:

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

关于javascript - JS 正则表达式不返回所有匹配的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32652675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com