Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

Can I write switch case in c# like this?

switch (string)

case [a..z]+

//   do something

case [A..Z]+

//   do something

....
like image 914
wang kai Avatar asked Mar 10 '17 00:03

wang kai


People also ask

Can I use regex in C?

A regular expression is a sequence of characters used to match a pattern to a string. The expression can be used for searching text and validating input. Remember, a regular expression is not the property of a particular language. POSIX is a well-known library used for regular expressions in C.

What programming languages support regex?

Programming languages like Perl and AWK, provides built-in regular expression capabilities, while others like Java and Python, support regular expressions through standard libraries. Perl supports a rich set of metacharacters, many of which were not supported by other languages previously.

Does regex work for other languages?

Short answer: yes. More specifically it depends on your regex engine supporting unicode matches (as described here).

What is regex in C sharp?

In C#, Regular Expression is a pattern which is used to parse and check whether the given input text is matching with the given pattern or not. In C#, Regular Expressions are generally termed as C# Regex. The . Net Framework provides a regular expression engine that allows the pattern matching.


1 Answers

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
like image 191
David Clarke Avatar answered Sep 21 '22 09:09

David Clarke