How do I get the name of captured groups in a C# Regex?

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);
}

Leave a Comment