tags:

views:

455

answers:

2

There is a way to get the name of a captured group in C#?

string line = "No.123456789  04/09/2009  999";
Regex regex = new Regex(@"(?<number>[\d]{9})  (?<date>[\d]{2}/[\d]{2}/[\d]{4})  (?<code>.*)");

GroupCollection groups = regex.Match(line).Groups;

foreach (Group group in groups)
{
    Console.WriteLine("Group: {0}, Value: {1}", ???, group.Value);
}

So I can get this result:

Group: [I don´t know what should go here], Value: 123456789  04/09/2009  999
Group: number, Value: 123456789
Group: date,   Value: 04/09/2009
Group: code,   Value: 999
+12  A: 

Use GetGroupNames to get the list of groups in an expression and then iterate over those, using the names as keys into the groups collection.

For example,

GroupCollection groups = regex.Match(line).Groups;

foreach (string groupName in regex.GetGroupNames())
{
    Console.WriteLine(
       "Group: {0}, Value: {1}",
       groupName,
       groups[groupName].Value);
}
Jeff Yates
Thank you! Exactly what I wanted. I never thought that this would be in the Regex object :(
Luiz Damim
+2  A: 

You should use GetGroupNames(); and the code will look something like this:

    string line = "No.123456789  04/09/2009  999";
    Regex regex = 
        new Regex(@"(?<number>[\d]{9})  (?<date>[\d]{2}/[\d]{2}/[\d]{4})  (?<code>.*)");

    GroupCollection groups = regex.Match(line).Groups;

    var grpNames = regex.GetGroupNames();

    foreach (var grpName in grpNames)
    {
        Console.WriteLine("Group: {0}, Value: {1}", grpName, groups[grpName].Value);
    }
Eran Betzalel
+1 Thank you Eran.
Luiz Damim