【问题标题】:Using RegEx in Dictionary在字典中使用正则表达式
【发布时间】:2016-11-09 13:41:03
【问题描述】:

我是 C# 新手,看来我需要使用 Regex 和 Dictionary<string, Action>

以下与我一起工作的示例,作为理解 C# 中的Regex 的测试:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{


    public static void Main()
    {

        string sPattern = "word1|word2";
        string input = "word2";

        Match result = Regex.Match(input, sPattern);

        Console.WriteLine(result);
    }
}

我尝试将其包含在Dictionary 中,如下所示,但失败了:

var functions = new Dictionary<Match, Action>();
functions.Add(Regex.Match(string, sPattern), CountParameters);

Action action;
if (functions.TryGetValue("word1|word2", out action)) {action.Invoke(); }

它给了我invalid expression string at Regex.Match(string, sPattern) 和cannot convert string to Match at .TryGetValue("word1|word2")

更新

我像下面这样重组了我的代码,所以我没有编译错误,但结果没有打印出来:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Program
{


    public static void Main()
    {

        string sPattern1 = "word1|word2";
        string sPattern2 = "word3|word4";

        string input = "word2";

        var functions = new Dictionary<string, Action>();
        functions.Add("word1", CountParameters);
        functions.Add("word3", SomeOtherMethodName);

        Action action;
        if (functions.TryGetValue((Regex.Match(input, sPattern1)).ToString(), out action))
        {
            action.Invoke();
        }
        else
        {
            // No function with that name
        }

    }


    public static void CountParameters()
    {
    Console.WriteLine("Fn 1");
    }

    public static void SomeOtherMethodName()
    {
    Console.WriteLine("Fn 2");
    }
}

如果 string input = "word1"; 以上是有效的但如果 string input = "word2"; 则不起作用而 RegEx 应根据 string sPattern = "word1|word2"; 将 word1 和 word2 视为相同

更新 2

如果不够清楚,上面的输出应该是:

  1. 在输入是 word1 或 word2 的情况下执行 CountParameters,因为考虑到上述模式中使用的 |,RegEx 应该认为它们相同。

  2. 在输入是 word3 或 word4 的情况下执行 SomeOtherMethodName,因为考虑到上述模式中使用的 |,RegEx 应该认为它们相同。

等等,以防我使用OR(即|)添加更多正则表达式

【问题讨论】:

    标签: c# regex dictionary .net-core


    【解决方案1】:

    我想你想要这样的东西:

    var input = "word2";
    var functions = new Dictionary<Regex, Action>
    {
        {new Regex("word1|word2"), CountParameters}
    };
    functions.FirstOrDefault(f => f.Key.IsMatch(input)).Value?.Invoke();
    

    【讨论】:

    • 你能详细说明一下吗,如果我的字典有很多对,比如:var functions = new Dictionary&lt;Regex, Action&gt; { {new Regex("word1|word2"), CountParameters}, {new Regex("word3|word4"), SomeOtherMethodName} };
    • 它将执行分配给第一个找到的与您的输入匹配的正则表达式的操作。
    • 我知道?. 是一个空条件运算符,但是如果我想执行命令或打印错误消息怎么办,有没有办法在这里使用TryGetValue?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2015-05-26
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多