8.2. Extracting Groups from a MatchCollection

Problem

You have a regular expression that contains one or more named groups, such as the following:

\\\\(?<TheServer>\w*)\\(?<TheService>\w*)\\

where the named group TheServer will match any server name within a UNC string, and TheService will match any service name within a UNC string.

You need to store the groups that are returned by this regular expression in a keyed collection (such as a Hashtable) in which the key is the group name.

Solution

The RegExUtilities class contains a method, ExtractGroupings, that obtains a set of Group objects keyed by their matching group name:

using System;
using System.Collections;
using System.Text.RegularExpressions;

public static ArrayList ExtractGroupings(string source, 
                                         string matchPattern,
                                         bool wantInitialMatch)
{
    ArrayList keyedMatches = new ArrayList( );
    int startingElement = 1;
    if (wantInitialMatch)
    {
        startingElement = 0;
    }

    Regex RE = new Regex(matchPattern, RegexOptions.Multiline);
    MatchCollection theMatches = RE.Matches(source);

    foreach(Match m in theMatches)
    {
        Hashtable groupings = new Hashtable( );

        for (int counter = startingElement; 
          counter < m.Groups.Count; counter++)
        {
            // If we had just returned the MatchCollection directly, the
            //  GroupNameFromNumber method would not be available to use
            groupings.Add(RE.GroupNameFromNumber(counter),
                           m.Groups[counter]);
        }

        keyedMatches.Add(groupings);
    }

    return (keyedMatches);
}

The ExtractGroupings method can be used in the following manner to extract ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.