Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use named group in C# regex switch/case?

I want to write a code that checks if it matches to a regular expression then prints matched string.

I found other question Can I use regex expression in c# with switch case?, but IsMatch method only returns boolean so I couldn’t retrieve named group string.

var filepath = @"path/to/file.txt";
foreach (string line File.ReadLines(filepath))
{
    switch (line)
    {
        case var s when new Regex(@"^(?<UserName>\w+) moved to (?<Position>\w+)$").IsMatch(s):
            // I have to know <UserName> and <Position> here.
            break;
        ...
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First, I’d suggest moving the regex construction itself outside the switch block – both for readability and to allow it to be reused.

Then, instead of using IsMatch, use the Match to return a Match, which you’d then check for success (potentially using a C# pattern match). For example:

using System.Text.RegularExpressions;

class Program
{
    private static void Main()
    {
        RunTest("Jon moved to XYZ");
        RunTest("Not a match");
    }

    private static readonly Regex UserMovementRegex = new Regex(@"^(?<UserName>\w+) moved to (?<Position>\w+)$");
    private static void RunTest(string line)
    {
        switch (line)
        {
            case string _ when UserMovementRegex.Match(line) is { Success: true } match:
                Console.WriteLine($"UserName: {match.Groups["UserName"]}");
                Console.WriteLine($"Position: {match.Groups["Position"]}");
                break;
            default:
                Console.WriteLine("No match");
                break;
        }
    }
}

The { Success: true } match part has two purposes:

  • It checks that the match is successful
  • It captures the result in a new match variable that you can use in the body of the case label
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading