2011-06-13 13 views
1

我不懂正則表達式,只做一個小任務,我不想坐下來學習 - 更不用說他們看起來很複雜。我想要做的事情是將一個段落傳遞給一個方法,並刪除一段以參數「begin」開頭並以參數「end」結尾的文本。在C#.NET中使用正則表達式刪除一段文字

public static string RemoveBetween(string wholeText, string begin, string end) 
    { 

    } 

例:

string myString = "one two three four five"; 
myString = RemoveBetween(myString, "two", "four"); 

最終的字符串將是 「一五」

+0

如果'end'在字符串中的'begin'之前(如RemoveBetween(myString,「four」,「two」)'),預期的行爲是什麼?或者如果找不到「開始」或「結束」?如果有多個「begin」或「end」或兩者出現,該怎麼辦? – 2011-06-13 16:58:01

+0

你並不需要使用正則表達式來實現你的目標。你不想「坐下來學習」是一種恥辱。正則表達式對於軟件開發人員來說非常有用。 – Bernard 2011-06-13 16:58:16

+0

@BertrandM結束從未開始,但可能涉及遞歸。在那種情況下,我需要刪除所有的孩子和孫子。如果找不到開始和結束,只需返回現有的字符串。來電者假定找不到開始和結束,或者他們都被找到。 – user246392 2011-06-13 17:01:27

回答

6
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; 
} 
+2

在使用正則表達式之前,您可能不想忘記在開始和結束字符串中跳過特殊字符。 – Qtax 2011-06-13 17:01:09

+0

@Qtax - 我同意;這只是一個顯示概念的簡單例子。 – KeithS 2011-06-13 17:05:56

+0

您可以使用Regex.Escape靜態方法轉義開始和結束字符串。這樣,用戶不需要知道您使用的是正則表達式(或避免字符如$或< – 2011-06-13 22:54:19

-2

也許是這樣的。

string myString = "one two three four five"; 
     myString = myString.Substring(0, myString.IndexOf("two")) + myString.Substring(myString.IndexOf("four") + "four".Length); 
+0

或者可能不是... – 2011-06-13 17:03:42

+0

我試過了,它的工作原理,只是知道這不是一個好習慣,但它應該適用於他 – 2011-06-13 17:05:05

0

下面是另一個例子,分步進行所以它更容易理解怎麼回事,

public static string RemoveBetween(string wholeText, string begin, string end) 
{ 
    int indexOfBegin = wholeText.IndexOf(begin); 
    int IndexOfEnd = wholeText.IndexOf(end); 

    int lenght = IndexOfEnd + end.Length - indexOfBegin; 

    string removedString = wholeText.Substring(indexOfBegin, lenght); 

    return wholeText.Replace(removedString, ""); 
} 
0

你肯定不需要爲正則表達式,它會爲你更容易檢查輸入是否不使用它們。

public static string RemoveBetween(string wholeText, string begin, string end) { 
    var beginIndex = wholeText.IndexOf(begin); 
    var endIndex = wholeText.IndexOf(end); 

    if(beginIndex < 0 || endIndex < 0 || beginIndex >= endIndex) { 
     return wholeText; 
    } 

    return wholeText.Remove(beginIndex, endIndex - beginIndex + end.Length); 
}