Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex non capturing groups in javascript

I'm a bit rusty on my regex and javascript. I have the following string var:

var subject = "javascript:loadNewsItemWithIndex(5, null);";

I want to extract 5 using a regex. This is my regex:

/(?:loadNewsItemWithIndex\()[0-9]+/)

Applied like so:

subject.match(/(?:loadNewsItemWithIndex\()[0-9]+/)

The result is:

loadNewsItemWithIndex(5

What is cleanest, most readable way to extract 5 as a one-liner? Is it possible to do this by excluding loadNewsItemWithIndex( from the match rather than matching 5 as a sub group?

like image 583
Benedict Cohen Avatar asked Sep 21 '11 19:09

Benedict Cohen


1 Answers

The return value from String.match is an array of matches, so you can put parentheses around the number part and just retrieve that particular match index (where the first match is the entire matched result, and subsequent entries are for each capture group):

var subject = "javascript:loadNewsItemWithIndex(5, null);";
var result = subject.match(/loadNewsItemWithIndex\(([0-9]+)/);
                                    //             ^      ^  added parens
document.writeln(result[1]);
                  //    ^ retrieve second match (1 in 0-based indexing)

Sample code: http://jsfiddle.net/LT62w/

Edit: Thanks @Alan for the correction on how non-capturing matches work.

Actually, it's working perfectly. Text that's matched inside a non-capturing group is still consumed, the same as text that's matched outside of any group. A capturing group is like a non-capturing group with extra functionality: in addition to grouping, it allows you to extract whatever it matches independently of the overall match.

like image 128
mellamokb Avatar answered Oct 05 '22 09:10

mellamokb