Gets the group name that corresponds to the specified group number.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"(?<city>[A-Za-z\s]+), (?<state>[A-Za-z]{2}) (?<zip>\d{5}(-\d{4})?)";
string[] cityLines = {"New York, NY 10003"};
Regex rgx = new Regex(pattern);
List<string> names = new List<string>();
int ctr = 1;
bool exitFlag = false;
do {
string name = rgx.GroupNameFromNumber(ctr);
if (! String.IsNullOrEmpty(name))
{
ctr++;
names.Add(name);
}
else
{
exitFlag = true;
}
} while (! exitFlag);
foreach (string cityLine in cityLines)
{
Match match = rgx.Match(cityLine);
if (match.Success)
Console.WriteLine("Zip code {0} is in {1}, {2}.",
match.Groups[names[3]],
match.Groups[names[1]],
match.Groups[names[2]]);
}
}
}
Related examples in the same category