Grouping constructs delineate sub-expressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in table 1.
Grouping construct |
Description |
( subexpression ) |
Captures the matched sub-expression and assigns it a zero-based ordinal number. |
(?< name >sub-expression) |
Captures the matched sub-expression into a named group. |
(?< name1 - name2 >sub-expression) |
Defines a balancing group definition. For more information, see the "Balancing Group Definition" section in Grouping Constructs in Regular Expressions. |
(?: sub-expression) |
Defines a non-capturing group. |
(?imnsx-imnsx:sub-expression) |
Applies or disables the specified options within sub-expression. For more information, see Regular Expression Options. |
(?= sub-expression) |
Zero-width positive look-ahead assertion. |
(?! sub-expression) |
Zero-width negative look-ahead assertion. |
(?<= sub-expression) |
Zero-width positive look-behind assertion. |
(?<! sub-expression) |
Zero-width negative look-behind assertion. |
(?> sub-expression) |
Non-backtracking (or "greedy") sub-expression. |
Table 1: Grouping constructs
Pattern |
Matches |
(\w)\1 |
"ee" in "deep" |
(?<double>\w)\k<double> |
"ee" in "deep" |
(((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$ |
"((1-3)*(3-1))" in "3+2^((1-3)*(3-1))" |
Write(?:Line)? |
"WriteLine" in "Console.WriteLine()" |
A\d{2}(?i:\w+)\b |
"A12xl", "A12XL" in "A12xl A12XL a12xl" |
\w+(?=\.) |
"is", "ran", and "out" in "He is. The dog ran. The sun is out." |
\b(?!un)\w+\b |
"sure", "used" in "unsure sure unity used" |
(?<=19)\d{2}\b |
"99", "50", "05" in "1851 1999 1950 1905 2003" |
(?<!19)\d{2}\b |
"51", "03" in "1851 1999 1950 1905 2003" |
[13579](?>A+B+) |
"1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC" |
Table 2: Examples for grouping constructs