开发者

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?


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.


I believe the following regex should work for you:

loadNewsItemWithIndex\(([0-9]+).*$

var test = new RegExp(/loadNewsItemWithIndex\(([0-9]+).*$/);
test.exec('var subject = "javascript:loadNewsItemWithIndex(5, null);";');

The break down of this is

loadNewsItemWithIndex = exactly that

\( = open parentheses 

([0-9]+) = Capture the number
.* = Anything after that number

$ = end of the line


This should suffice:

<script>
var subject = "javascript:loadNewsItemWithIndex(5, null);";
number = subject.match(/[0-9]+/);
alert(number);
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜