Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (?: do in a regular expression

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.

like image 984
Graham Avatar asked Jan 03 '13 11:01

Graham


People also ask

What does (?: Mean in regex?

(?:...) 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.

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does /[ (]* regular expression indicate in Javascript?

4. What does /[^(]* regular expression indicate? Explanation: The [^…] character class is used to match or draw any one character not between the brackets.

What the \b will do in a regular expression?

Simply put: \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b. A “word character” is a character that can be used to form words. All characters that are not “word characters” are “non-word characters”.


1 Answers

(?:) 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

like image 62
Matti Virkkunen Avatar answered Oct 07 '22 19:10

Matti Virkkunen