【发布时间】: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
如果不够清楚,上面的输出应该是:
在输入是 word1 或 word2 的情况下执行
CountParameters,因为考虑到上述模式中使用的|,RegEx 应该认为它们相同。在输入是 word3 或 word4 的情况下执行
SomeOtherMethodName,因为考虑到上述模式中使用的|,RegEx 应该认为它们相同。
等等,以防我使用OR(即|)添加更多正则表达式
【问题讨论】:
标签: c# regex dictionary .net-core