What does (?: do in a regular expression

眉间皱痕 提交于 2019-12-21 03:41:17

问题


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.


回答1:


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




回答2:


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.




回答3:


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




回答4:


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.


来源:https://stackoverflow.com/questions/14138161/what-does-do-in-a-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!