Computer Science Canada

[Regex-tut] Non-Capturing Groups

Author:  wtd [ Sat Nov 13, 2004 11:11 pm ]
Post subject:  [Regex-tut] Non-Capturing Groups

Going way back

Going back to our old example:

code:
/^ \s* ( [hH]ello | [tT]oodles ) ,? \s+ world \s* $/x


Let's say I don't actually want to capture the greeting or parting message, and I'm just using the parentheses to group things. Why should I capture it and have that capturing group mess up the numbering scheme?

I shouldn't

I should use a non-capturing group instead. So instead of:

code:
( )


I'll use:

code:
(?: )


Putting it together

code:
/^ \s* (?: [hH]ello | [tT]oodles ) ,? \s+ world \s* $/x

Author:  templest [ Sat Nov 13, 2004 11:42 pm ]
Post subject: 

What the hell are all these posts? Could they not have been put into one thread? Eh

Author:  Hikaru79 [ Sat Nov 13, 2004 11:43 pm ]
Post subject: 

He wanted to make them short and simple. Easier to digest that way Very Happy Don't complain, just read them ^ ^

Author:  wtd [ Sat Nov 13, 2004 11:45 pm ]
Post subject: 

Thanks. That pretty much sums it up (it helps that Hikaru79 here saw me say that on IRC Wink ).

General Programming doesn't get much traffic anyway, and regular expressions are delightfully general, and not specific to any given language.


: