2

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?

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

3 Comments

but isn't the first match foo.bar? Or does it do the search from the right hand side?
Thanks. I'm still not sure that I fully understand what's going on there, but at least I can get it to work. The term "non capturing group" has given me enough to do more research (since googling ?: doesn't work)
@stib - No problem! Search SO for "capturing group" to learn all about the wonders of the parentheses in regular expressions :)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.