Hasan A Yousef Hasan A Yousef - 28 days ago 8
C# Question

Using RegEx in Dictionary

I'm new to C#, and it looks I need to use

Regex
with
Dictionary<string, Action>


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


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(); }


It gave me
invalid expression string at Regex.Match(string, sPattern)
and
cannot convert string to Match at .TryGetValue("word1|word2")


UPDATE

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


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


UPDATE 2

In case it was not clear enough, the output of the above should be:


  1. 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.

  2. 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
|

Answer

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();