开发者

Performance issues with Regex class inside a loop

I have a data table containing two columns (pattern and neworder) and cca 100 rows (all with different patterns).

What I am doing is matching an input string with pattern (grouped matches), and if match occurs I want to rearrange retrieved groups with Regex.Replace command.

The thing is that Regex does not act very friendly when being used inside a loop. Since I have to match input string against more then one pattern, and rearrange the appearance of the output string the only way for me to complete this task is to use Regex class. But that does not look like a proper solution since it significantly drops the performance.

The code looks like this

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.开发者_Go百科Replace(input_string, neworder);
    }

}


If you use the static methods to do the matching, .NET automatically caches the compiled Regex objects for you.

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

It only caches the 15 most recently used objects by default, so you would want to increase that by adjusting the Regex.CacheSize property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜