在字典中使用RegEx [英] Using RegEx in Dictionary
问题描述
我是C#的新手,看来我需要将Regex
与Dictionary<string, Action>
一起使用
I'm new to C#, and it looks I need to use Regex
with Dictionary<string, Action>
下面的工作示例与我一起测试,以了解C#中的Regex
:
The below working example with me, as testing of understanding the Regex
in C#:
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
中,如下所示,但失败了:
I tried to include it in Dictionary
as below, but failed:
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")
更新
我按如下所示重组了代码,因此没有编译错误,但结果没有打印出来:
I restructured my code like below, so I've no compiling error, but nothing is printed out as a result:
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");
}
}
如果字符串输入="word1",则上述方法有效.但如果字符串输入="word2",则不起作用;正则表达式应该根据string sPattern = "word1|word2";
The above is working if string input = "word1"; but not working if string input = "word2"; while the RegEx should consider both word1 and word2 as the same based on the string sPattern = "word1|word2";
更新2
如果还不够清楚,则上面的输出应为:
In case it was not clear enough, the output of the above should be:
-
在输入为word1或word2的情况下执行
CountParameters
,因为考虑到以上模式中使用的|
,RegEx应该将它们视为相同.
Executing
CountParameters
in case the input is word1 or word2, as the RegEx should consider them the same considering the|
used in the pattern above.
在输入为word3或word4的情况下执行SomeOtherMethodName
,因为考虑到以上模式中使用的|
,RegEx应该将它们视为相同.
Executing SomeOtherMethodName
in case the input is word3 or word4, as the RegEx should consider them the same considering the |
used in the pattern above.
依此类推,以防万一我使用|
and so on, in case I added more RegEx expression using the OR
which is |
推荐答案
我认为您想要这样的东西:
I think you want something like this:
var input = "word2";
var functions = new Dictionary<Regex, Action>
{
{new Regex("word1|word2"), CountParameters}
};
functions.FirstOrDefault(f => f.Key.IsMatch(input)).Value?.Invoke();
这篇关于在字典中使用RegEx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!