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

PythonServer Side ProgrammingProgramming

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.

Published on 10-Jan-2018 13:35:20