Are optional non-capturing groups redundant?
Is the following regex:
(?:wo)?men
semantically equivalent to the following regex?
(wo)?men
Are optional non-capturing groups redundant?
Is the following regex:
(?:wo)?men
semantically equivalent to the following regex?
(wo)?men
Your
(?:wo)?men
and(wo)?men
are semantically equivalent, but technically are different, namely, the first is using a non-capturing and the other a capturing group. Thus, the question is why use non-capturing groups when we have capturing ones?Non-caprturing groups are of help sometimes.
NOTE this does not pertain to Java regex engine, nor to PHP or .NET regex engines.
Also, it is just makes our matches cleaner:
It does not seem a good idea to re-factor existing regular expressions to convert capturing to non-capturing groups, since it may ruin the code or require too much effort.