Reputation: 10139
I have a confusion when reading regular expression written by others, my question is parentheses ()
could only be used for capture group? Or we could use it to make regular expression more elegant to read by group logical set of operations together, especially for long regular expression?
I ask this since I sometimes see after people write long regular expression, they write additional parentheses even if they do not need to know capture group match information -- I mean even if they just need to know if the whole regular expression match or not, they still add some parentheses.
Upvotes: 1
Views: 3157
Reputation: 785058
Parentheses are used for grouping and that would make regex engine capture the sub pattern inside the parentheses.
If you don't want to capture the text inside using non-capturing group by using this syntax:
(?:...)
This will also save some memory while processing the long and complex regex.
See more on Non capturing groups
A basic & simple example on how ad where ()
should be placed carefully if regex is this
^\w+|\d+$
Where we are selecting word at start or digits at end in the input:
foo -a123 bar baz 123
Thus we are matching foo
and 123
.
If you place brackets ()
like this:
^(\w+|\d+)$
then your match will fail as we are asserting presence of both anchors ^
and $
around a word OR a number in input.
Correct regex with brackets would be:
(?:^\w+|\d+$)
Upvotes: 2