如何在C#中编译正则表达式

时间:2012-07-23 08:23:22

标签: c# regex

我有一个如下所示的代码

private bool Set(string stream, string inputdata) 
  {

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


 return retval;

}

somwhere我发现兑现和编译将紧固正则表达式比较,我得到下面显示的代码,但我不知道如何在Set()方法中使用此代码,任何人都可以修改Set()方法以遵守下面显示的代码

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

仍然是Regex.IsMatch我做了exp.IsMatch,但那是私有变量,所以我不知道如何继续那个

1 个答案:

答案 0 :(得分:2)

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