2011-03-13 56 views
0

所以基本上,我有一個這樣的字符串:C#正則表達式替換

Some Text Here | More Text Here | Even More Text Here 

而且我希望能夠與New Text更換兩杆之間的文本,所以它最終會像:

Some Text Here | New Text | Even More Text Here 

我假設最好的方式是與正則表達式...所以我試了一堆東西,但無法得到任何工作...幫助?

回答

5

對於一個簡單的情況就是這樣,最好apprach是一個簡單的字符串分割:

string input = "foo|bar|baz"; 
string[] things = input.Split('|'); 
things[1] = "roflcopter"; 
string output = string.Join("|", things); // output contains "foo|roflcopter|baz"; 

這依賴於幾件事情:

  • 總是有3管道分隔文本字符串。
  • 管道之間沒有微不足道的空間。

要解決第二,這樣做:

for (int i = 0; i < things.Length; ++i) 
    things[i] = things[i].Trim(); 

從每個元素的開頭和結尾刪除空格。

與正則表達式的一般規則是,他們通常應該是你最後的手段;不是你的第一個。 :)

+1

+1務實的做法。我和下一個人一樣喜歡正則表達式,但如果更簡單的方法起作用,我就會全力以赴。 – Nate 2011-03-13 02:43:49

+0

確實。編寫看起來無害的正則表達式也很容易,這些正則表達式令人吃驚(通常在無法找到匹配的情況下)。如果我能用基本的字符串方法得到我想要的東西,比如'Split','StartsWith','EndsWith'或'Contains',那麼我通常會這樣做。 – 2011-03-13 02:46:54

2

如果你想使用正則表達式...試試這個:

String testString = "Some Text Here | More Text Here | Even More Text Here"; 
Console.WriteLine(Regex.Replace(testString, 
         @"(.*)\|([^|]+)\|(.*)", 
         "$1| New Text |$3", 
         RegexOptions.IgnoreCase));