javascript 非捕获组仍在比赛中显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18178597/
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-10-27 10:58:49  来源:igfitidea点击:

non-capture group still showing in match

javascriptregex

提问by vin

I know this topic has been thoroughly covered on StackOverflow, but I can't for the life of me get my regular expression to work. So without further repetitive ado ...

我知道这个主题已经在 StackOverflow 上得到了彻底的介绍,但是我一生都无法让我的正则表达式起作用。所以没有进一步重复的麻烦......



This is what I have.

这就是我所拥有的。

String: <p model='cat'></p>

细绳: <p model='cat'></p>

Regex: .match(/(?:model=')(.*)(?:')/g)

正则表达式: .match(/(?:model=')(.*)(?:')/g)

This is what my expression returns: model='cat'

这是我的表达式返回的内容: model='cat'

This is what I want: cat

这就是我要的: cat



Why isn't my non capture group ignored? Is it that I don't understand what a non-capturing group does? Why isn't my Regex working?

为什么我的非捕获组没有被忽略?是不是我不明白非捕获组是做什么的?为什么我的正则表达式不起作用?

回答by Dallas

The entire match will always be group 0, you need to access that specific group (group 1 in this case since the first group is non-capture), you can do it like this:

整个比赛将始终是第 0 组,您需要访问该特定组(在本例中为第 1 组,因为第一组未捕获),您可以这样做:

var str = "<p model='cat'></p>";
var regex = /(?:model=')(.*)(?:')/g
var match = regex.exec(str);
alert(match[1]); // cat

Fiddle

小提琴

Also, I suppose you are probably wanting several matches within str, you could do that like this:

另外,我想您可能想要在 str 中进行多个匹配,您可以这样做:

var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";
var regex = /(?:model=')([^']*)/g
var matches = [];
var match;
while (match = regex.exec(str)) {
  matches.push(match[1]);
}
alert(matches); // cat,dog,horse

Fiddle

小提琴

回答by JLRishe

A non-capturing group is basically a non-group ― a way to use parentheses without actually capturing that part of the pattern as a group.

非捕获组基本上是一个非组 - 一种使用括号而不实际将模式的那部分作为一个组捕获的方法。

It looks like what you're actually looking for are the "match prefix but exclude" group (?<=)and the "match suffix but exclude" group (?=).

看起来您实际上正在寻找的是“匹配前缀但排除”组(?<=)和“匹配后缀但排除”组(?=)

If you use these, you get the desired result:

如果你使用这些,你会得到想要的结果:

var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";
var regex = /(?<=model=')[^']*(?=')/g
var matches = str.match(regex);

console.log(matches);