I'm trying to use a pattern like this in a javascript regexp:
"foo.bar".match(/foo\.(buz|bar)/)
but instead of returning foo.bar as I expect, it returns an array:
["foo.bar", "bar"]
I don't get it. How do I 开发者_开发问答match foo.bar and foo.buz?
You are correctly matching "foo.bar" or "foo.buz", but since you have a grouping ((...)
), the returned array includes more than one item:
[Full Match, Match 1, Match 2, ... , Match N]
According to the spec, the result is always an array, and the full matched text will be element 0. Elements 1...N will be the matches (in your case, "bar" or "buz").
If you want make sure your array is length 1, then you want to put ?:
after every (
to make it a non-capturing group (See https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions, syntax (?:x)
):
"foo.bar".match(/foo\.(?:buz|bar)/)
However, this is not necessary, as you can always just reference result[0]
for the full match.
Incidentally, the /g
option (see the docs again) will also get rid of the capturing groups from the result array. Because /g
executes a global search, the elements in the result array are used to display all full matches (and in your case given, there's just one).
Regex matching works in that way, that the first element of group is a whole string that is matched by whole regex. The same way if you will make a "big" group.
/(foo\.(buz|bar))/
The second and all next elements are those you matched by your own - so it is buz
or bar
:
(buz|bar)
In that case if you want not to batch just buz/bar you can exclude this group using ?:
"foo.bar".match(/foo\.(?:buz|bar)/)
Your result will looks like:
["foo.bar"]
But it will still be an array with one element.
精彩评论