Grouping constructs delineate subexpressions of a regular expression and typically capture substrings of an input string. Grouping constructs include the language elements listed in the following table.
Pattern | Description | Sample | Matches |
( subexpression ) | Captures the matched subexpression and assigns it a one-based ordinal number. | (\w)\1 | "ee" in "deep" |
(?<name> subex) | Captures the matched subexpression into a named group. | (?<double>\w)\k<double> | "ee" in "deep" |
(?<name1-name2> subex) | Defines a balancing group definition. | (((?'Open'\()[^\(\)]*)+((?'Close-Open'\))[^\(\)]*)+)*(?(Open)(?!))$ | "((1-3)*(3-1))" in "3+2^((1-3)*(3-1))" |
(?:subex) | Defines a noncapturing group. | Write(?:Line)? | "WriteLine" in "Console.WriteLine()", "Write" in "Console.Write(value)" |
(?imnsx-imnsx: subex) | Applies or disables the specified options within subexpression. | A\d{2}(?i:\w+)\b | "A12xl", "A12XL" in "A12xl A12XL a12xl" |
(?= subex) | Zero-width positive lookahead assertion. | \w+(?=\.) | "is", "ran", and "out" in "He is. The dog ran. The sun is out." |
(?! subex) | Zero-width negative lookahead assertion. | \b(?!un)\w+\b | "sure", "used" in "unsure sure unity used" |
(?<= subex) | Zero-width positive lookbehind assertion. | (?<=19)\d{2}\b | "99", "50", "05" in "1851 1999 1950 1905 2003" |
(?<! subex) | Zero-width negative lookbehind assertion. | (? | "51", "03" in "1851 1999 1950 1905 2003" |
(?> subex) | Nonbacktracking (or "greedy") subexpression. | [13579](?>A+B+) | "1ABB", "3ABB", and "5AB" in "1ABB 3ABBC 5AB 5AC" |