我可以在带开关盒的c#中使用正则表达式吗?

wan*_*kai 7 c# regex

我可以像这样在c#中编写switch case吗?

switch (string)

case [a..z]+

//   do something

case [A..Z]+

//   do something

....
Run Code Online (Sandbox Code Playgroud)

Dav*_*rke 19

是的你可以在C#7:

switch (someString)
{
    case var someVal when new Regex(@"[a..z]+").IsMatch(someVal):
        // do something
        break;
    case var someVal when new Regex(@"[A..Z]+").IsMatch(someVal):
        // do something
        break;
}
Run Code Online (Sandbox Code Playgroud)


Jak*_*eMc 10

从 C# 8.0 开始,现在的答案是肯定的!...有点像。

在 8.0 中,引入了switch 表达式。您可以使用它来匹配许多不同风格的图案,如下所示。

string myValueBeingTested = "asdf";
        
string theResultValue = myValueBeingTested switch
{
    var x when 
        Regex.IsMatch(x, "[a..z]+") => "everything is lowercase",
    var y when
        Regex.IsMatch(y, "[A..Z]+") => "EVERYTHING IS UPPERCASE",
    "Something Specific"            => "The Specific One",
    _                               => "The default, no match scenario"
};
Run Code Online (Sandbox Code Playgroud)

工作原理:switch 表达式需要一个可以将结果输入到其中的变量。上面的示例使用theResultValue变量来实现这一点。接下来,将上面表示的范围表达式传递到开关中。熟悉的case构造被替换为模式表达式,后跟标记,并一起称为表达式臂手臂标记右侧的任何内容都将最终出现在结果变量中。myValueBeingTested=>

通常,switch 表达式要求模式是编译时常量,并且您不能在switch 表达式内执行任意代码。但是,我们可以通过使用子句来使用大小写when模式,以利用正则表达式,如上所示。每个案例都需要连接到具有不同一次性变量的不同x中,(和y以上)。

上面显示的第三个分支是一个编译时常量字符串,用于在需要时匹配某些特定文本。上面显示的第四个使用该_模式,这是一种类似于旧default:关键字的通配符。您还可以使用null代替或补充来_与其他任何内容分开处理空情况。

在我的.NET Fiddle 示例中尝试一下。


Mic*_*ael 6

使用 _ 作为丢弃对大卫的优秀答案进行了小幅改进。只是一个非常简单的字符串值作为例子。

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());
    }
}
Run Code Online (Sandbox Code Playgroud)