开发者

javascript regexp can't find way to access grouped results

re = //?(\w+)/(\w+)/ s = '/projects/new' s.match(re)

I have this regular expression which I will use to sieve out the branch name, e.g., projects, and the 'tip' name, e.g., new

I read that one can have access to the gr开发者_如何学Couped results with $1, $2, and so on, but I can't seem to get it to work, at least in Firebug console

When I run the above code, then run

 RegExp.$1

it shows

""

Same goes on for $2.

any ideas?

Thanks!


Without the g flag, str.match(regexp) returns the same as regexp.exec(str). And that is:

The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. If the match fails, the exec method returns null.

So you can do this:

var match = s.match(re);
match[1]


match gives you an array of the matched expressions:

> s.match(re)[1]
"projects"
> s.match(re)[2]
"new"


I you are accessing the array of matches the wrong way do something like:

re = /\/?(\w+)\/(\w+)/
s = '/projects/new'
var j = s.match(re)

alert(j[1]);
alert(j[2]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜