如何将Python正则表达式转换为C#?

如何将Python正则表达式转换为C#?,c#,python,regex,C#,Python,Regex,在我的Python代码中,我有如下内容: Type1 = [re.compile("-" + d + "-") for d in "49 48 29 ai au2".split(' ')] Type2 = [re.compile("-" + d + "-") for d in "ki[0-9] 29 ra9".split(' ')] Everything = {"Type1": Type1, Type2: Type2} 和一个小函数来返回输入字符串的类型 def getInputType

在我的Python代码中,我有如下内容:

Type1 = [re.compile("-" + d + "-")  for d in "49 48 29 ai au2".split(' ')]
Type2 = [re.compile("-" + d + "-")  for d in "ki[0-9] 29 ra9".split(' ')]

Everything = {"Type1": Type1, Type2: Type2}
和一个小函数来返回输入字符串的类型

def getInputType(input):
    d = "NULL"
    input = input.lower()
    try:
        for type in Everything:
            for type_d in Everything[type]:
                code = "-" + input.split('-')[1] + "-"
                if type_d.findall(code):
                    return type
    except:
        return d
    return d

在C#中定义这些多个正则表达式有一行等价物吗?还是我应该分别声明它们?简而言之,将其转换为C#的好方法是什么?

我认为一个相当简单的翻译应该是:

Dictionary<string, List<Regex>> everything = new Dictionary<string, List<Regex>>()
{
    { "Type1", "49 48 29 ai au2".Split(' ').Select(d => new Regex("-" + d + "-")).ToList() },
    { "Type2", "ki[0-9] 29 ra9".Split(' ').Select(d => new Regex("-" + d + "-")).ToList() },
}

string GetInputType(string input)
{
    var codeSegments = input.ToLower().Split('-');
    if(codeSegments.Length < 2) return "NULL";

    string code = "-" + codeSegments[1] + "-";
    var matches = everything
        .Where(kvp => kvp.Value.Any(r => r.IsMatch(code)));

    return matches.Any() ? matches.First().Key : "NULL";
}
Dictionary everything=newdictionary()
{
{“Type1”,“49 48 29 ai au2”.Split('').Select(d=>newregex(“-”+d+“-”).ToList(),
{“Type2”,“ki[0-9]29 ra9”.Split('').Select(d=>newregex(“-”+d+“-”).ToList(),
}
字符串GetInputType(字符串输入)
{
var codeSegments=input.ToLower().Split('-');
if(codeSegments.Length<2)返回“NULL”;
字符串代码=“-”+代码段[1]+“-”;
var匹配=一切
其中(kvp=>kvp.Value.Any(r=>r.IsMatch(代码));
返回matches.Any()?matches.First().键:“NULL”;
}

太棒了!谢谢你的指导。