Home > front end >  Is there a better way to get the group name of a RegEx Match in C#?
Is there a better way to get the group name of a RegEx Match in C#?

Time:04-24

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.

CodePudding user response:

Your groups are not optional, so they will always be a success if the match is successful. Also, 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.Cast<Match>().Where(m => m.Success))
{
    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);
  •  Tags:  
  • c#
  • Related