capture group still showing in match

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


This is what I have.

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

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

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

This is what I want: 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?


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

Fiddle

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

Fiddle

链接地址: http://www.djcxy.com/p/74784.html

上一篇: 在一个条件下“被捕获的组等于”

下一篇: 仍然在比赛中表现出来的比赛