2010-11-30 165 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>"); 
} 
相关问题