If you want to retrieve a specific group name you can use the Regex
.
GroupNameFromNumber
method.
//regular expression with a named group
Regex regex = new Regex(@"(?<Type1>AAA)|(?<Type2>BBB)", RegexOptions.Compiled);
//evaluate results of Regex and for each match
foreach (Match m in regex.Matches("AAABBBAAA"))
{
//loop through all the groups in current match
for(int x = 1; x < m.Groups.Count; x ++)
{
//print the names wherever there is a succesful match
if(m.Group[x].Success)
Console.WriteLine(regex.GroupNameFromNumber(x));
}
}
Also, There is a string indexer on the GroupCollection
. object that is accesible on the Match
.
Groups
property, this allows you to access a group in a match by name instead of by index.
//regular expression with a named group
Regex regex = new Regex(@"(?<Type1>AAA)|(?<Type2>BBB)", RegexOptions.Compiled);
//evaluate results of Regex and for each match
foreach (Match m in regex.Matches("AAABBBAAA"))
{
//print the value of the named group
if(m.Groups["Type1"].Success)
Console.WriteLine(m.Groups["Type1"].Value);
if(m.Groups["Type2"].Success)
Console.WriteLine(m.Groups["Type2"].Value);
}