Javascript:如何在 RegEx .exec 结果中获得多个匹配项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11270302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:13:29  来源:igfitidea点击:

Javascript: How to get multiple matches in RegEx .exec results

javascriptregexnode.jsv8

提问by Trindaz

When I run

当我跑

/(a)/g.exec('a a a ').length

I get

我得到

2

but I thought it should return

但我认为它应该回来

3

because there are 3 as in the string, not 2!

因为a字符串中有 3 个,而不是 2 个!

Why is that?

这是为什么?

I want to be able to search for all occurances of a string in RegEx and iterate over them.

我希望能够在 RegEx 中搜索所有出现的字符串并遍历它们。

FWIW: I'm using node.js

FWIW:我正在使用 node.js

回答by Andrew Cheong

exec()is returning only the set of captures for the first match, not the set of matches as you expect. So what you're really seeing is $0(the entire match, "a") and $1(the first capture)--i.e. an array of length 2. exec()meanwhile is designed so that you can call it againto get the captures for the nextmatch. From MDN:

exec()只返回第一次匹配的捕获集,而不是您期望的匹配集。所以你真正看到的是$0(整个匹配,“a”)和$1(第一次捕获)——即长度为 2 的数组。 exec()同时被设计成你可以再次调用它来获取下一次匹配的捕获. 来自MDN

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property).

如果您的正则表达式使用“g”标志,您可以多次使用 exec 方法来查找同一字符串中的连续匹配项。当您这样做时,搜索从由正则表达式的 lastIndex 属性指定的 str 子字符串开始(测试也将推进 lastIndex 属性)。

回答by mVChr

You could use matchinstead:

你可以match改用:

'a a a'.match(/(a)/g).length  // outputs: 3

回答by Jeanne Boyarsky

You are only matching the first a. The reason the length is two is that it is finding the first match and the parenthesized group part of the first match. In your case they are the same.

您只匹配第一个 a。长度为 2 的原因是它正在查找第一个匹配项和第一个匹配项的括号组部分。在您的情况下,它们是相同的。

Consider this example.

考虑这个例子。

var a = /b(a)/g.exec('ba ba ba ');
alert(a);

It outputs ba, a. The array length is still 2, but it is more obvious what is going on. "ba" is the full match. ais the parenthesized first grouping match.

它输出ba, a. 数组长度仍然是2,但更明显的是发生了什么。“ba”是完全匹配。 a是括号中的第一个分组匹配。

The MDN documentationsupports this - that only the first match and contained groups are returned. To find all matches, you'd use match() as stated by mVChr.

MDN文档支持这一点-只有第一场比赛和含有组返回。要查找所有匹配项,您可以使用 mVChr 所述的 match()。

回答by ajaykools

while loopcan help you

while 循环可以帮助您

x = 'a a a a';
y = new RegExp(/a/g);
while(null != (z=y.exec(x))) {
   console.log(z);     // output: object
   console.log(z[0]);  // ouput: "a"
}

If you add counter then you get length of it.

如果添加计数器,则会得到它的长度。

x = 'a a a a';
counter = 0;
y = new RegExp(/a/g);
while(null != (z=y.exec(x))) {
   console.log(z);     // output: object
   console.log(z[0]);  // output: "a"
   counter++;
}
console.log(counter);  // output: 4

This is quite safe, even if it doesn't find any matching then it just exits and counter will be 0

这是很安全的,即使它没有找到任何匹配,它也会退出并且计数器将为 0

Main intention is to tell how RegExp can be used to loop and get all values from string of same matched RegExp

主要目的是说明如何使用 RegExp 循环并从相同匹配 RegExp 的字符串中获取所有值

回答by ?mega

Code:

代码:

alert('a a a'.match(/(a)/g).length);

Output:

输出:

3

回答by Taki

regexp.exec(str)returns the first match or the entire match and the first capture (when re = /(a)/g;) as mentionned in other answers

regexp.exec(str)返回第一个匹配项或整个匹配项和第一个捕获(when re = /(a)/g;),如其他答案中所述

const str = 'a a a a a a a a a a a a a';
const re = /a/g;

const result = re.exec(str);
console.log(result);

But it also remembersthe position after it in regexp.lastIndexproperty.

但它也会记住它在regexp.lastIndex属性中的位置。

The next call starts to search from regexp.lastIndexand returns the next match.

下一个调用开始搜索regexp.lastIndex并返回下一个匹配项。

If there are no more matches then regexp.execreturns null and regexp.lastIndexis set to 0.

如果没有更多匹配项,则regexp.exec返回 null 并regexp.lastIndex设置为 0。

const str = 'a a a';
const re = /a/g;

const a = re.exec(str);
console.log('match : ', a, ' found at : ', re.lastIndex);

const b = re.exec(str);
console.log('match : ', b, ' found at : ', re.lastIndex);

const c = re.exec(str);
console.log('match : ', c, ' found at : ', re.lastIndex);

const d = re.exec(str);
console.log('match : ', d, ' found at : ', re.lastIndex);

const e = re.exec(str);
console.log('match : ', e, ' found at : ', re.lastIndex);

That's why you can use a while loop that will stop when the match is null

这就是为什么您可以使用 while 循环在匹配结束时停止的原因 null

const str = 'a a a';
const re = /a/g;

while(match = re.exec(str)){
  console.log(match, ' found at : ', match.index); 
}