public static string RemoveBetween(string wholeText, string begin, string end)
{
Regex.Replace(wholeText, String.Format("{0}.*?{1}", Regex.Escape(begin), Regex.Escape(end)), String.Empty);
}
容易。認真學習正則表達式;他們需要大量的解析並將其減少到一行代碼。
作爲對比,這裏的東西逼近你有沒有正則表達式做什麼:
public static string RemoveBetween(string wholeText, string begin, string end)
{
var result = wholeString;
var startIndex = result.IndexOf(begin);
while(startIndex >=0)
{
var endIndex = result.IndexOf(end) + end.Length;
//TODO: Define behavior for when the end string doesn't appear or is before the begin string
result = result.Substring(0,startIndex) + result.Substring(endIndex+1, result.Length - endIndex);
startIndex = result.IndexOf(begin);
}
return result;
}
如果'end'在字符串中的'begin'之前(如RemoveBetween(myString,「four」,「two」)'),預期的行爲是什麼?或者如果找不到「開始」或「結束」?如果有多個「begin」或「end」或兩者出現,該怎麼辦? – 2011-06-13 16:58:01
你並不需要使用正則表達式來實現你的目標。你不想「坐下來學習」是一種恥辱。正則表達式對於軟件開發人員來說非常有用。 – Bernard 2011-06-13 16:58:16
@BertrandM結束從未開始,但可能涉及遞歸。在那種情況下,我需要刪除所有的孩子和孫子。如果找不到開始和結束,只需返回現有的字符串。來電者假定找不到開始和結束,或者他們都被找到。 – user246392 2011-06-13 17:01:27