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:
它用于url匹配,上面的示例匹配以下url:
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.
正在使用的正则表达式版本是Classic ASP提供的版本,如果有帮助的话,它正在服务器上运行。
2 个解决方案
#1
17
(?:)
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
反向引用是您可以在表达式中引用的部分或可能的替换(通常通过说\ 1或$ 1等 - 取决于风格)。在编程语言中使用正则表达式时,通常也可以从匹配中提取它们。使用(?:)的唯一原因是避免创建新的反向引用,这可以避免增加组号,并节省(通常可忽略不计的数量)内存
#2
4
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.
如果你正在做这样的事情:(abc)(?:123)(def)你将获得1美元的abc和2美元的def,但123只会匹配。
#1
17
(?:)
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
反向引用是您可以在表达式中引用的部分或可能的替换(通常通过说\ 1或$ 1等 - 取决于风格)。在编程语言中使用正则表达式时,通常也可以从匹配中提取它们。使用(?:)的唯一原因是避免创建新的反向引用,这可以避免增加组号,并节省(通常可忽略不计的数量)内存
#2
4
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.
如果你正在做这样的事情:(abc)(?:123)(def)你将获得1美元的abc和2美元的def,但123只会匹配。