Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match Regular expression from a dictionary in C#

I am trying to have some sort of Data Object (I'm thinking a dictionary) to hold a TON of regular expressions as keys, then I need to take a string of text, and match against them to get the actual value from the Dictionary. I need an efficient way to do this for a large set of data.

I am in C# and I'm not sure where to begin.

like image 809
Chris Kooken Avatar asked Sep 10 '09 22:09

Chris Kooken


2 Answers

Why not use LINQ?

Dictionary<string, string> myCollection = new Dictionary<string, string>();

myCollection.Add("(.*)orange(.*)", "Oranges are a fruit.");
myCollection.Add("(.*)apple(.*)", "Apples have pips.");
myCollection.Add("(.*)dog(.*)", "Dogs are mammals.");
// ...

string input = "tell me about apples and oranges";

var results = from result in myCollection
              where Regex.Match(input, result.Key, RegexOptions.Singleline).Success
              select result;

foreach (var result in results)
{
    Console.WriteLine(result.Value);
}

// OUTPUT:
//
// Oranges are a fruit.
// Apples have pips.
like image 197
gpmcadam Avatar answered Nov 13 '22 21:11

gpmcadam


Remember that if you are planning on using a regex more than once you can create a regex object as compiled and re-use it to reduce overhead.

Regex RegexObject = new Regex(Pattern, RegexOptions.Compiled);

Using this model you would be best storing a regex object rather than the pattern string.

like image 29
stevehipwell Avatar answered Nov 13 '22 21:11

stevehipwell