非捕获组仍然在比赛中显示 [英] non-capture group still showing in match

查看:61
本文介绍了非捕获组仍然在比赛中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道StackOverflow已经完全涵盖了这个主题,但我不能为我的生活让我的正则表达式工作。所以没有进一步的重复... ...

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 ...

这就是我所拥有的。

字符串:< p model ='cat'>< / p>

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

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

This is what my expression returns: model='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?

推荐答案

整个匹配将始终为0组,您需要访问该特定组(本例中自第1组以来group is non-capture),你可以这样做:

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:

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

小提琴

另外,我想你可能想要在str中进行几场比赛,你可以这么做像这样:

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

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

小提琴

这篇关于非捕获组仍然在比赛中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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