我有一個文字處理器,其中包括數百Regex.Replace調用。他們中的許多人使用相同的文本。他們將例如刪除空格和不想要的字符,把周圍的號碼中的括號,刪除列入黑名單的話,等將多個Regex.Replace調用
有沒有一種方法,使具有不同圖案的多用更換一個單一的電話嗎?我很想知道,因爲我的代碼目前很慢,我想這會節省一些週期。
我有一個文字處理器,其中包括數百Regex.Replace調用。他們中的許多人使用相同的文本。他們將例如刪除空格和不想要的字符,把周圍的號碼中的括號,刪除列入黑名單的話,等將多個Regex.Replace調用
有沒有一種方法,使具有不同圖案的多用更換一個單一的電話嗎?我很想知道,因爲我的代碼目前很慢,我想這會節省一些週期。
是的,這裏是一個簡單的例子:
myText = new Regex("hello").Replace(myText, "");
myText = new Regex("goodBye").Replace(myText, "");
可以替換爲:
myText = new Regex("hello|goodbye").Replace(myText, "");
這可能會或可能不會提高你的應用程序的性能。這真的取決於。
如果它只是一個空格,不想要的字符和列入黑名單的話,你爲什麼不嘗試串/ StringBuilder的功能呢?
string newString = oldString.Replace('`','\0');
string newString = oldString.Replace("blackword","");
也可以看看這裏:Replace multiple words in string和Replace Multiple String Elements in C#
櫃面,有人正在以取代使用正則表達式多值的多個字符串。 該代碼
"this is sentence.".Replace("is", "are");
//output- thare are sentence.
....因爲它會取代每個匹配的字符。它不會區分「this」和「is」。 您可以使用字典和正則表達式是這樣的:
Dictionary<string, string> replacements = new Dictionary<string, string>();
replacements.Add("is", "are");
replacements.Add("this", "these");
string temp;
foreach (KeyValuePair<string,string> replacement in replacements)
{
address = Regex.Replace(address, @"\b" + replacement.Key + "\\b", replacement.Value);
}
注意:小心與@"\b" + replacement.Key + "\\b"
部分。它給了我很多頭痛。