Reputation: 7018
I am little confused understanding the regex pattern below from this link:
(?:x)
Matches 'x' but does not remember the match. The parentheses are called non-capturing parentheses, and let you define subexpressions for regular expression operators to work with. Consider the sample expression
/(?:foo){1,2}/
. If the expression was/foo{1,2}/
, the{1,2}
characters would apply only to the last 'o' in 'foo'. With the non-capturing parentheses, the{1,2}
applies to the entire word 'foo'. For more information, see Using parentheses below.
I am not able to understand these two points:
Consider the sample expression /(?:foo){1,2}/
. If the expression was /foo{1,2}/
, the {1,2}
characters would apply only to the last 'o
' in 'foo
'.
With the non-capturing parentheses, the {1,2}
applies to the entire word 'foo
'
Upvotes: 0
Views: 46
Reputation: 522636
Actually, as far as I know, the non capturing group has nothing to do with your immediate question, and both of the following patterns would match the same things:
/(?:foo){1,2}/
/(foo){1,2}/
The parentheses tell the regex engine that you want the quantity rule {1,2}
to apply to the entire quantity. Without the parentheses, the quantity defaults to applying to the immediately preceding character o
:
/foo{1,2}/
This would match foo
and fooo
.
Upvotes: 1