2010-11-30 164 views
12

我有一些可怕的文本,我正在使用幾個c#正則表達式進行清理。有一個讓我難以理解的問題是文本中有很多'\ r \ n'字符串,實際字符不是換行符。C#如何Regex.Replace「 r n」(實際字符,而不是換行符)

我已經試過:

content = Regex.Replace(content, "\\r\\n", ""); 

和:

content = Regex.Replace(content, "\r\n", ""); 

,但他們都沒有工作。最後,我不得不使用:

content = content.Replace("\\r\\n", "\r\n"); 

以完成項目,但不能在正則表達式中做到這一點讓我煩惱。

+0

可以幫助嗎? http://stackoverflow.com/questions/1981947/how-can-i-remove-rn-from-a-string-in-c-can-i-use-a-regex – SubniC 2010-11-30 08:44:54

+3

content.Replace(@「\ r \ n「,」\ r \ n「)是您的最佳選擇。 – VVS 2010-11-30 08:46:30

回答

20

\r\n在正則表達式中也有特殊含義,所以反斜槓需要被轉義。然後,將這些反斜槓需要轉義爲C#字符串,導致

content = Regex.Replace(content, "\\\\r\\\\n", ""); 

content = Regex.Replace(content, @"\\r\\n", ""); 
-3

胡亂猜測這裏:

var bslash = System.IO.Path.DirectorySeparatorChar.ToString(); 

content = content.Replace(bslash + "r" + bslash + "n", ""); 
5

這是一個好主意,進入寫在C#中的正則表達式時使用逐字字符串(@"example")的習慣。在這種情況下,你需要這樣的:

content = Regex.Replace(content, @"\\r\\n", "\r\n"); 

否則,您必須逃脫每個反斜線兩次:一旦逃離它在C#字符串,然後第二次逃脫他們的正則表達式。因此,一個反斜槓將變爲四個反斜槓與標準字符串文字。

3
content = Regex.Replace(content, "\\\\r\\\\n", ""); 

可能會奏效。更多信息here

引用:以及

在字面C#字符串,在 C++和許多其他.NET語言中, 反斜槓是轉義字符。文字字符串「\\」是 的一個單一的 反斜槓。在正則表達式中, 反斜槓也是一個轉義字符。 正則表達式\\匹配 單個反斜槓。這個常規的 表達式作爲C#字符串,變成 「\\\\」。沒錯:4個反斜槓 匹配一個。

注:我不得不寫8個反斜槓在倒數第二句話讓4個反斜線會得到顯示;-)

2

在指定的輸入字符串,Regex.Replace替換爲匹配正則表達式模式的字符串指定替換字符串。

一個典型用法是

string input = "This is text with far too  much " + " whitespace."; 
    string pattern = "\\s+"; 
    string replacement = " "; 
    Regex rgx = new Regex(pattern); 
    string result = rgx.Replace(input, replacement); 

似乎並不喜歡這就是你正在嘗試做的。

0

這個問題很古老,但一直在變化。

string temp = Regex.Replace(temp, "\\n", " "); 

或更好足夠

string temp = Regex.Replace("tab d_space newline\n content here :P", @"\s+", " "); 
//tab d_space newline content here :P 

這適用於通用的Windows應用程序,可能其他人也。

0

更好的&簡單的答案就在這裏。它適用於我使用正則表達式。

public static string GetMultilineBreak(this string content) 
{ 
    return Regex.Replace(content, @"\r\n?|\n", "<br>"); 
} 
相關問題