表示法(问号和冒号表示法)

我有以下 Java 正则表达式,我没有写,我试图修改:

^class-map(?:(\\s+match-all)|(\\s+match-any))?(\\s+[\\x21-\\x7e]{1,40})$
^                                 ^

类似于 这个

注意第一个问号。这是否意味着这个小组是可选的?在相应的 )之后已经有一个问号。冒号在正则表达式中有特殊含义吗?

Regex 编译得很好,并且已经有 JUnit 测试显示它是如何工作的。只是我有点搞不懂为什么第一个问号和冒号会在那里。

80719 次浏览

(?: starts a non-capturing group. It's no different to ( unless you're retrieving groups from the regex after use. See What is a non-capturing group? What does a question mark followed by a colon (?:) mean?.

A little late to this thread - just to build on ryanp's answer.

Assuming you have the string aaabbbccc

Regular Expression

(a)+(b)+(c)+

This would give you the following 3 groups that matched:

['a', 'b', 'c']

Regular Expression with non-capturing parenthesis

Use the ?: in the first group

(?:a)+(b)+(c)+

and you would get the following groups that matched:

['b', 'c']

Hence why it is called "non-capturing parenthesis"

Example use case:

Sometime you use parenthesis for other things. For example to set the bounds of the | or operator:

"New (York|Jersey)"

In this case, you are only using the parenthesis for the or | switch, and you don't really want to capture this data. Use the non-capturing parenthesis to indicate that:

"New (?:York|Jersey)"