Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-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?

like image 649
vin Avatar asked Aug 12 '13 01:08

vin


People also ask

What does a non-capturing group mean?

It makes the group non-capturing, which means that the substring matched by that group will not be included in the list of captures.

Why use a non-capturing group?

A non-capturing group lets us use the grouping inside a regular expression without changing the numbers assigned to the back references (explained in the next section). This can be very useful in building large and complex regular expressions.

How do you write a non-capturing group in regex?

Sometimes, you may want to create a group but don't want to capture it in the groups of the match. To do that, you can use a non-capturing group with the following syntax: (?:X)

What is capturing group?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .


1 Answers

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

like image 117
Dallas Avatar answered Sep 20 '22 23:09

Dallas