Regex groups are created by placing part of a regular expression inside parentheses. Groups allows to apply a quantifier to the entire group or to restrict alternation to part of the regex. Besides grouping part of a regular expression together, parentheses also create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses.
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
.
If capturing the match isn't needed, the regular expression can be optimized into Set(?:Value)?
. The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group.
The question mark after the opening bracket is unrelated to the question mark at the end of the regex. The final question mark is the quantifier that makes the previous token optional. This quantifier cannot appear after an opening parenthesis, because there is nothing to be made optional at the start of a group. Therefore, there is no ambiguity between the question mark as an operator to make a token optional and the question mark as part of the syntax for non-capturing groups.