I have come across a regular expression that I don’t fully understand – can somebody help me in deciphering it:
^home(?:\/|\/index\.asp)?(?:\?.+)?$
It is used in url matching and the above example matches the following urls:
home
home/
home/?a
home/?a=1
home/index.asp
home/index.asp?a
home/index.asp?a=1
It seems to me that the question marks within the brackets (?: don’t do anything. Can somebody enlighten me.
The version of regex being used is the one supplied with Classic ASP and is being run on the server if that helps at all.
(?:)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 (by saying
\1or$1etc – depending on flavor). You can also extract them from a match afterwards when using regex in a programming language. The main reason for using(?:)is to avoid creating a new backreference, which avoids incrementing the group number which is especially important if you’re repeating a group and do not want to have unpredictable group numbers, and saves (a usually negligible amount of) memory