Can I use regex expression in c# with switch case?

Yes you can in C# 7 (and nobody noticed I had used the incorrect range character in the character class .. instead of -). Updated now with a slightly more useful example that actually works:

using System.Text.RegularExpressions;
string[] strings = {"ABCDEFGabcdefg", "abcdefg", "ABCDEFG"};
Array.ForEach(strings, s => {
    switch (s)
    {
        case var someVal when new Regex(@"^[a-z]+$").IsMatch(someVal):
            Console.WriteLine($"{someVal}: all lower");
            break;
        case var someVal when new Regex(@"^[A-Z]+$").IsMatch(someVal):
            Console.WriteLine($"{someVal}: all upper");
            break;
        default:
            Console.WriteLine($"{s}: not all upper or lower");
            break;
    }
});

Output:

ABCDEFGabcdefg: not all upper or lower
abcdefg: all lower
ABCDEFG: all upper

A minor refinement on David's excellent answer using _ as a discard. Just a very simple string value as an example.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string userName = "Fred";
        int something = 0;

        switch (true)
        {                
            case bool _ when Regex.IsMatch(userName, @"Joe"):
                something = 1;
                break;

            case bool _ when Regex.IsMatch(userName, @"Fred"):
                something = 2;
                break;

            default:            
                break;
        }    
        Console.WriteLine(something.ToString());
    }
}

You should be able to do something like this:

using System.Text.RegularExpressions;

private void fauxSwitch(string caseSwitch)
{
    if(Regex.Match(caseSwitch, @"[a..z]+").Success)
    {
        //do something
        return;
    }

    if(Regex.Match(caseSwitch, @"[A..Z]+").Success)
    {
        //do something
        return;
    }

    /*default*/
    //do something
}

Although, Pattern matching in C#7 is probably the better option.

Tags:

C#

Regex