[英]Replace {#Text} and {$Text} in a string, in a performant way
注意:這不是一個簡單的字符串替換問題。
我的情況如下,我有一個大字符串(<1024B,但> 300B),它將有{#String}和{$ String}。
更具體的{#SomethingBlahBlah}和{$ SomeOtherThingBlahBlah},所以在regexp {#w +}和{$ w +}中
我的第一個問題是,regexps是唯一的方法嗎? 我喜歡字符串替換解決方案等,其次如果是,有沒有辦法只做一個編譯的正則表達式並進行單次傳遞?
Linq可以通過任何機會幫忙嗎?
對於大字符串和幾個不同的替換,我建議使用StringBuilder。
StringBuilder sb = new StringBuilder(input);
sb.Replace("{$String}", "Real Value");
sb.Replace("{$SomeOtherThingBlahBlah}", "Another Real Value");
return sb.ToString();
操作將在內存中發生,並且在調用ToString()之前不會分配新字符串。
您可以使用以下方法之一:
選項1
正則表達式:
\{(?:#|\$)(\w+)}
文本:
{#SomethingBlahBlah} and {$SomeOtherThingBlahBlah}
返回:
Result 1
1. SomethingBlahBlah
Result 2
1. SomeOtherThingBlahBlah
選項2
正則表達式:
(\{(?:#|\$)(?:\w+)})
文本:
{#SomethingBlahBlah} and {$SomeOtherThingBlahBlah}
返回:
Result 1
1. {#SomethingBlahBlah}
Result 2
1. {$SomeOtherThingBlahBlah}
IndexOf vs Regex:使用Stopwatch
測試超過100000次迭代,使用500~長度的字符串。
方法IndexOf
public static string Re(string str)
{
int strSIndex = -1;
int strEIndex = -1;
strSIndex = str.IndexOf("{#");
if (strSIndex == -1) strSIndex = str.IndexOf("{$");
if (strSIndex == -1) return str;
strEIndex = str.IndexOf("}");
if (strEIndex == -1) return str;
if (strEIndex < strSIndex)
{
strSIndex = str.IndexOf("{$");
if (strSIndex == -1) return str;
}
str = str.Substring(0, strSIndex) + str.Substring(strEIndex + 1);
return Re(str);
}
正則表達式方法
Regex re = new Regex(@"\{(?:#|\$)(\w+)}", RegexOptions.Compiled);
re.Replace(str, "");
結果(很少替換):
Fn: IndexOf
Ticks: 1181967
Fn: Regex
Ticks: 1482261
請注意,regex設置為在迭代之前編譯。
結果(大量替換):
Fn: Regex
Ticks: 19136772
Fn: IndexOf
Ticks: 37457111
String.Replace("SomethingBlahBlah", "SomeOtherThingBlahBlah")
編輯:剛剛在這個帖子中找到了Jon Skeet的精彩答案。
Regex需要更多時間來替換文本而不是使用String.Replace方法。 但是Regex通過文本操作為您提供了巨大的力量。 LINQ沒有使用字符串的直接方法。 它只能使用現有功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.