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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With