Reputation:
I have a .NET Regex which looks similar to:
(?<Type1>AAA)|(?<Type2>BBB)
I'm using the Matches method against a sample string e.g. "AAABBBAAA"
, and then iterating over the matches.
My goal is to find the match types, using the regex match group, so for this regex it will be:
I couldn't find any GetGroupName
method. Please help.
Upvotes: 14
Views: 36656
Reputation: 48402
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);
}
Upvotes: 10
Reputation: 1500535
Is this the sort of thing you're looking for? It uses Regex.GroupNameFromNumber
so you don't need to know the group names outside the regex itself.
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
Regex regex = new Regex("(?<Type1>AAA)|(?<Type2>BBB)");
foreach (Match match in regex.Matches("AAABBBAAA"))
{
Console.WriteLine("Next match:");
GroupCollection collection = match.Groups;
// Note that group 0 is always the whole match
for (int i = 1; i < collection.Count; i++)
{
Group group = collection[i];
string name = regex.GroupNameFromNumber(i);
Console.WriteLine("{0}: {1} {2}", name,
group.Success, group.Value);
}
}
}
}
Upvotes: 20
Reputation: 6453
Try this:
var regex = new Regex("(?<Type1>AAA)|(?<Type2>BBB)");
var input = "AAABBBAAA";
foreach (Match match in regex.Matches(input))
{
Console.Write(match.Value);
Console.Write(": ");
for (int i = 1; i < match.Groups.Count; i++)
{
var group = match.Groups[i];
if (group.Success)
Console.WriteLine(regex.GroupNameFromNumber(i));
}
}
Upvotes: 0