代码之家  ›  专栏  ›  技术社区  ›  mko

循环内Regex类的性能问题

  •  1
  • mko  · 技术社区  · 14 年前

    我有一个数据表,包含两列(pattern和neworder)和CCA 100行(都有不同的模式)。

    我要做的是将输入字符串与模式匹配(分组匹配),如果匹配发生,我希望使用regex.replace命令重新排列检索到的组。

    问题是,当在循环中使用regex时,它的行为并不十分友好。因为我必须根据多个模式匹配输入字符串,并重新排列输出字符串的外观,所以完成此任务的唯一方法是使用regex类。但这看起来不是一个合适的解决方案,因为它会显著降低性能。

    代码看起来像这样

    DataTable dt = this.GetPatterns();
    DataRow dr;
    System.Collections.IEnumerator ie = dt.Rows.GetEnumerator();
    while(ie.MoveNext() && !found)
    {
        dr = ((DataRow)ie.Current);
        pattern = dr["pattern"].ToString();
        neworder= dr["neworder"].ToString();
    
        Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
        Match match = reg.Match(input_string);
    
        if (match.Success)
        {
        found = true;
        output = reg.Replace(input_string, neworder);
        }
    
    }
    
    1 回复  |  直到 11 年前
        1
  •  4
  •   Alan Moore Chris Ballance    14 年前

    if (Regex.Match(input, pattern, options).Success)
    {
      output = Regex.Replace(input, pattern, neworder, options);
    }
    

    Regex.CacheSize