'Is there a better way to get the group name of a RegEx Match in C#?

I'm currently creating a Syntax Highlighter in C# and WPF. So far it works but it feels like I could get the value of a named group better.

Here is an example with an example RegEx on how I'm doing it right now:

private void Match(string r)
{
    var matches = Regex.Matches(r, @"(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)", RegexOptions.Multiline);
    for (int i = 0; i < matches.Count; i++)
    {
        if (matches[i].Success)
        {
            for (int j = 0; j < matches[i].Groups.Count; j++)
            {
                if (matches[i].Groups[j].Success)
                {
                    switch (matches[i].Groups[j].Name)
                    {
                        case "duplicateWord":
                            ProcessDuplicate(matches[i].Groups[j].Value);
                            break;
                        case "nextWord":
                            ProcessNext(matches[i].Groups[j].Value);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }
}

Of course this isn't the RegEx I'm using I have about 10 groups in mine. So I'm hoping for a better solution. Another thought would be to use different regular expressions but that will most likely lessen performance even further.

Thank you all in advance.



Solution 1:[1]

Here are a couple of notes:

  • Your groups are not optional, so they will always be a success if the match is successful.

  • All matches returned by Regex.Matches() are always successful. A Match returned by Regex.Match() can be unsuccessful, but that doesn't apply here.

  • You don't really have to iterate the groups. Just access them directly using the indexer.

You can simplify your code significantly by writing something like this:

foreach (Match match in matches)
{
    ProcessDuplicate(match.Groups["duplicateWord"].Value);
    ProcessNext(match.Groups["nextWord"].Value);
}

If some of the groups are optional, you can check the Success property of those groups only:

if (match.Groups["someGroup"].Success)
    SomeMethod(match.Groups["someGroup"].Value);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1