2009-11-08 60 views
1

我有這個簡單的正則表達式替換基於常規的,反正是有提高其性能(也許也爲其增色不少?)初學正則表達式替換性能問題

public static string stripshrapnel(string str) 
{ 
     string newstr = str.Trim(); 
     newstr = Regex.Replace(newstr, @"-", ""); 
     newstr = Regex.Replace(newstr, @"'", ""); 
     newstr = Regex.Replace(newstr, @",", ""); 
     newstr = Regex.Replace(newstr, @"""", ""); 
     newstr = Regex.Replace(newstr, @"\?", ""); 
     newstr = Regex.Replace(newstr, @"\#", ""); 
     newstr = Regex.Replace(newstr, @"\;", ""); 
     newstr = Regex.Replace(newstr, @"\:", ""); 
     //newstr = Regex.Replace(newstr, @"\(", ""); 
     //newstr = Regex.Replace(newstr, @"\)", ""); 
     newstr = Regex.Replace(newstr, @"\+", ""); 
     newstr = Regex.Replace(newstr, @"\%", ""); 
     newstr = Regex.Replace(newstr, @"\[", ""); 
     newstr = Regex.Replace(newstr, @"\]", ""); 
     newstr = Regex.Replace(newstr, @"\*", ""); 
     newstr = Regex.Replace(newstr, @"\/", ""); 
     newstr = Regex.Replace(newstr, @"\\", ""); 
     newstr = Regex.Replace(newstr, @"&", "&"); 
     newstr = Regex.Replace(newstr, @"&amp", "&"); 
     newstr = Regex.Replace(newstr, @" ", " "); 
     newstr = Regex.Replace(newstr, @"&nbsp", " "); 
     return newstr; 
} 

謝謝 馬特

回答

9

你可以結合大多數的表達式,直到你最終只有三個:

public static string stripshrapnel(string str) 
{ 
     string newstr = str.Trim(); 
     newstr = Regex.Replace(newstr, @"[-',""?#;:+%[\]*/\\\\]", ""); 
     newstr = Regex.Replace(newstr, @"&?", "&"); 
     newstr = Regex.Replace(newstr, @" ?", " "); 
     return newstr; 
} 
+0

Fantastic Gumbo!,謝謝你,有沒有人有任何想法這將是多快(這是一個粗略的%?)? – WickedW 2009-11-08 14:22:18

+0

@WickedW:目前的表現難以接受嗎?如果是這樣,你有沒有分析應用程序,以確定這是否是一個瓶頸?通常最好避免過早優化。 (雖然我肯定會考慮用Gumbo的替換你原來的代碼。) – TrueWill 2009-11-08 16:29:25

+0

@WickedW:我不指望它快得多,因爲它做了相同的工作,但只是以不同的方式。但是你爲什麼不自己評估一下呢? – Gumbo 2009-11-08 16:33:32

3

由於您使用零正則表達式功能也許有另一種方式。看起來C#有一個用於字符串的Replace方法,相反,我認爲在執行正則表達式時使用了很多額外的功能,而不是簡單的替換。

+0

+1用於在可能的情況下用正則表達式替換 – bguiz 2009-11-08 12:45:04

+1

String.Replace沒有字符集並且需要與問題中類似的代碼。 Gumbo的解決方案速度更快,可讀性更強。 – 2009-11-08 13:02:22