Documentation for ?: in regex?

后端 未结 6 726
日久生厌
日久生厌 2020-12-08 14:36

A while ago, I saw in regex (at least in PHP) you can make a capturing group not capture by prepending ?:.

Example

$str = \'big blue b         


        
6条回答
  •  孤城傲影
    2020-12-08 15:05

    It's available on the Subpatterns page of the official documentation.

    The fact that plain parentheses fulfill two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 99, and the maximum number of all subpatterns, both capturing and non-capturing, is 200.

    It's also good to note that you can set options for the subpattern with it. For example, if you want only the sub-pattern to be case insensitive, you can do:

    (?i:foo)bar
    

    Will match:

    • foobar
    • Foobar
    • FoObar
    • ...etc

    But not

    • fooBar
    • FooBAR
    • ...etc

    Oh, and while the official documentation doesn't actually explicitly name the syntax, it does refer to it later on as a "non-capturing subpattern" (which makes complete sense, and is what I would call it anyway, since it's not really a "group", but a subpattern)...

提交回复
热议问题