O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required