2010-11-26 104 views
1

我有一個數據表包含兩列(模式和neworder)和cca 100行(所有具有不同的模式)。循環中的正則表達式類的性能問題

我在做什麼是匹配輸入字符串與模式(分組匹配),如果匹配發生,我想用Regex.Replace命令重新排列檢索到的組。

事情是,正則表達式在循環內部使用時不會表現得非常友好。因爲我必須將輸入字符串與多個模式匹配,並重新排列輸出字符串的外觀,所以我完成此任務的唯一方法是使用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); 
    } 

} 

回答

4

如果使用靜態方法來做匹配,.NET會自動緩存編譯的regex對象爲您服務。

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

它只緩存默認情況下,15點最近期使用的對象,所以你會希望增加通過調整Regex.CacheSize財產。

+0

不,你的建議是有道理的,但它不適用於我。我添加了Regex.CacheSize = 200,但我最終遇到了同樣的問題。我甚至試圖創建一個Regex對象數組,所以我不必再次使用同一個對象,但這也沒有幫助。 – mko 2010-11-26 10:02:42