2

Possible Duplicate:
Non capturing group?

I'm learning regex in JavaScript, and the (?:x) character or "non-capturing parentheses" just doesn't make sense to me. If you don't want the match to be remembered why not just abandon parentheses altogether? What's the advantage of using /(?:x)/ instead of just /x/?

Community
  • 1
  • 1
Rocky DeHart
  • 173
  • 2
  • 9
  • I believe I saw that one while researching, but the example seemed complex. Since I'm learning I need simple answers. :) – Rocky DeHart Jul 10 '12 at 14:26

4 Answers4

13

Because you might need the parentheses for other reasons. For example, suppose you want to capture the digit at the end of abababababab9. If you wrote ab*(\d) then it would match abbbbbbbbb9. You need to parenthesize the ab so that the * operator will repeat the whole thing. (ab)*(\d). But maybe you don't care about how many times ab was repeated. That's where you use (?:): (?:ab)*(\d).

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
3

You need it to define sub-patterns to be used in alternative matches or with quantifiers, that would apply to entire sub-pattern without wasting capture slot. For example, you can use (?:) together with | to provide alternate matches in middle of regexp without capturing it.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
3

Consider the following cases:

(?:aa|bb|cc)

(?:abc)?

You can use the non-capturing group to match patterns that have more complex sub-patterns. In certain cases using the non-capturing group syntax will result in a more efficient regular expression as well.

Cecchi
  • 1,525
  • 9
  • 9
1

If you don't want the match to be remembered why not just abandon parentheses altogether? What's the advantage of using /(?:x)/ instead of just /x/?

It used when you want to group chars, but you don't want to remember them. If you remove the parentheses, you can't group a sequence of characters. So, for instance:

/foo|bar/.test("foo") // true
/foo|bar/.test("bar") // true

If you want to achieve a pattern that match foor and fbar you have to group the characters in the middle:

/f(?:oo|ba)r/.test("fbar") // true
/f(?:oo|ba)r/.test("foor") // true

Of course you can also group and remember the group, but if instead test your using match or other methods where the array returned is significant to you, then you have to use (?: instead.

ZER0
  • 24,846
  • 5
  • 51
  • 54