我有一些可怕的文字,我正在使用几个c#正则表达式进行清理。令我难过的一个问题是文本中有许多'\ r \ n'字符串,实际字符不是换行符。
我试过了:
content = Regex.Replace(content, "\\r\\n", "");
和
content = Regex.Replace(content, "\r\n", "");
但它们都不起作用。最后我不得不使用:
content = content.Replace("\\r\\n", "\r\n");
让项目完成,但在正则表达式中无法做到这一点让我很烦。
答案 0 :(得分:24)
\r
和\n
在Regex中也有特殊含义,因此需要对反斜杠进行转义。然后,需要为c#字符串转义这些反斜杠,导致
content = Regex.Replace(content, "\\\\r\\\\n", "");
或
content = Regex.Replace(content, @"\\r\\n", "");
答案 1 :(得分:7)
在C#中编写正则表达式时,养成使用逐字字符串文字(@"example"
)的习惯是个好主意。在这种情况下,你需要这个:
content = Regex.Replace(content, @"\\r\\n", "\r\n");
否则你必须转义每个反斜杠两次:一次在C#字符串中转义它,然后第二次为正则表达式转义它们。因此,单个反斜杠将成为带有标准字符串文字的四个反斜杠。
答案 2 :(得分:3)
content = Regex.Replace(content, "\\\\r\\\\n", "");
可能会奏效。更多信息here。
引用:
在文字C#字符串中,以及在 C ++和许多其他.NET语言 反斜杠是一个转义字符。该 文字字符串“\\”是单个字符串 反斜杠。在正则表达式中, 反斜杠也是一个转义字符。 正则表达式\\匹配a 单反斜杠。这个常规 表达式作为C#字符串,变为 “\\\\”。那是对的:4个反斜杠 匹配一个。
注意:我必须在最后一个句子中写下8个反斜杠,这样就会显示4个反斜杠; - )
答案 3 :(得分: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);
这似乎不是你想要做的。
答案 4 :(得分:1)
更好的&简单的答案就在这里。它适用于我使用正则表达式。
public static string GetMultilineBreak(this string content)
{
return Regex.Replace(content, @"\r\n?|\n", "<br>");
}
答案 5 :(得分: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应用程序,也可能适用于其他应用程序。
答案 6 :(得分:-3)
疯狂猜测:
var bslash = System.IO.Path.DirectorySeparatorChar.ToString();
content = content.Replace(bslash + "r" + bslash + "n", "");