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

时间:2012-09-23 19:26:58

标签: 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(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#的好方法是什么?

1 个答案:

答案 0 :(得分:1)

我认为一个相当直接的翻译是:

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";
}