2011-04-23 122 views
3

我想以後[/quote]C#正則表達式替換 n

,以消除任何新行字符我有這個目前:

Comment = Regex.Replace(Comment, @"[/quote](\n){1,}", "[/quote]");

但它似乎並沒有做任何事情!

例子:

[/quote] 


hey nice quote blah blah 

轉到

[/quote]hey nice quote blah blah 

回答

3

你確定你的字符串以\n(UNIX-sty le行尾),而不是\r\n(Windows風格的行結尾)?

此外,實現[...]在正則表達式表示一個字符類,所以你[/quote]單個字符要麼是/quot,或者e匹配。您必須將[設爲\[以匹配開括號字符。

把它們放在一起(和簡化{1,}的簡寫+),並嘗試這個辦法:

Regex.Replace(Comment, @"\[/quote\][\r\n]+", "[/quote]"); 
+0

非常感謝你!那麼'[\ r \ n]'是否匹配他們中的任何一個呢? – 2011-04-23 15:47:55

+1

@Tom:它至少匹配其中的一個,因此所有這些匹配:'\ r','\ n','\ r \ n','\ n \ r','\ r \ r \ r \ r \,\ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ n \ r \ n \ n \ n \ r'等 – 2011-04-23 15:55:47

0

添加一個 「+」 後 「\ n」 匹配所有\ n的

+0

似乎不工作 – 2011-04-23 15:41:14

0

還需要躲避換行符 [/ quote] [\\ n] +

+0

這不似乎工作etiehr – 2011-04-23 15:45:36

0

嘗試使用這個表達式

string strRegex = @"\[/quote\][\n\r]+"; 
Regex myRegex = new Regex(strRegex); 

string strReplace = "[/quote]"; 
return myRegex.Replace(strTargetString, strReplace);