January 24, 2017
Hot Topics:

Named and Non-Capturing Groups in .NET Regular Expressions

  • March 21, 2005
  • By Tom Archer
  • Send Email »
  • More Articles »

Non-Capturing Groups

Groups are not always defined in order to create sub-matches. Sometimes groups get created as a side effect of the parenthetical syntax used to isolate a part of the expression such that modifiers, operators, or quantifiers can act on the isolated part of the expression. Irregardless of your reason for isolating a part of the pattern, once you do it using the parenthesis symbols, the regular expressions parser creates Group objects for that group within each Match object's group collection (Groups).

An example might better explain what I mean. Say you have a pattern to search a string for occurrences of the words "on", "an", and "in":

If you tested this pattern with the following function, which simply displays all the groups of each match, you'd find that each match results in five groups:
void DisplayGroups(String* input, String* pattern)
    StringBuilder* results = new StringBuilder();

    Regex* rex = new Regex(pattern);

    // for all the matches
    for (Match* match = rex->Match(input); 
         match = match->NextMatch())
      results->AppendFormat(S"Match {0} at {1}\r\n",

      // for all of THIS match's groups
      GroupCollection* groups = match->Groups;
      for (int i = 0; i < groups->Count; i++)
        results->AppendFormat(S"\tGroup {0} at {1}\r\n",
  catch(Exception* pe)

Figure 1 shows the results of running the following code using the DisplayGroups function:

// Example usage of the DisplayGroups function
DisplayGroups(S"Tommy sat on a chair, in a room", 

Figure 1: Using Parentheses in Patterns Always Creates Groups

Therefore, for efficiency