I have come across a regular expression that I don\'t fully understand - can somebody help me in deciphering it:
^home(?:\\/|\\/index\\.asp)?(?:\\?.+)?$
<
its really easy every parentheses will create a variable in the memory so you can use the parentheses value afterward so to not save it in memory just put :? in the parentheses like this (?:) and then fill the rest as you need. that's it and nothing else
It's a non-capture group, which essentially is the same as using (...)
, but the content isn't retained (not available as a back reference).
If you're doing something like this: (abc)(?:123)(def)
You'll get abc
in $1
and def
in $2
, but 123
will only be matched.
From documentation:
(?:...)
A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
(?:)
creates a non-capturing group. It groups things together without creating a backreference.
A backreference is a part you can refer to in the expression or a possible replacement (usually by saying \1
or $1
etc - depending on flavor). You can also usually extract them from a match afterwards when using regex in a programming language. The only reason for using (?:)
is to avoid creating a new backreference, which avoids incrementing the group number, and saves (a usually negligible amount of) memory