vettori
vettori

Reputation: 761

How to compile the regularexpression in C#

I have code as shown below for detecting if a string has any matches with a regular expression, both of which are sent in as parameters of this method.

private bool Set(string stream, string inputdata) 
{

    bool retval = Regex.IsMatch(inputdata, stream, RegexOptions.IgnoreCase);
    return retval;
}

I've read that caching and compiling the expression will make the regex comparison faster, and I have a sample of such code shown below, but I don't know how to modify the code in my original Set() method, above, to take advantage of compilation.

How would I modify the Set() method to apply the code shown below?

static Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();

private Regex BuildRegex(string pattern)
{
    Regex exp;
    if (!regexCache.TryGetValue(pattern, out exp))
    {
        var newDict = new Dictionary<string, Regex>(regexCache);
        exp = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        newDict.Add(pattern, exp);
        regexCache = newDict;
     }

     return exp;
 }

Instead of Regex.IsMatch, I used exp.IsMatch, but that's a private variable, so I don't know how to proceed.

Upvotes: 3

Views: 3463

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89171

private bool Set(string stream, string inputdata) 
{
    var regex = BuildRegex(stream);
    bool retval = regex.IsMatch(inputdata);
    return retval;
}

static Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();

private static Regex BuildRegex(string pattern)
{
    Regex exp;

    if (!regexCache.TryGetValue(pattern, out exp))
    {
        exp = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        regexCache.Add(pattern, exp);
    }

    return exp;
}

Upvotes: 3

Related Questions