What does “?:” mean in a Python regular expression?


Non capturing groups

If  we do not want a group to capture its match, we can write this regular expression as Set(?:Value). The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. 

The regex Set(Value)? matches Set or SetValue. In the first case, the first (and only) capturing group remains empty. In the second case, the first capturing group matches Value. The question mark appearing at the end is the quantifier that makes the previous token optional. 

Set(?:Value) matches Setxxxxx, i.e., all those strings starting with Set but not followed by Value. Such would be non capturing groups.

color=(?:red|green|blue) is another regex with a non-capturing group. This regex has no quantifiers.

Regex flavors that support named capture often have an option to turn all unnamed groups into non-capturing groups.

Updated on: 13-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements