C# C“如何使用Regex.Replace”\r\n“;(实际字符,而不是换行符)
我有一些可怕的文本,我正在用几个c#正则表达式清理它们。让我困惑的一个问题是,文本中有许多“\r\n”字符串,实际字符不是换行符 我试过:C# C“如何使用Regex.Replace”\r\n“;(实际字符,而不是换行符),c#,.net,regex,string,C#,.net,Regex,String,我有一些可怕的文本,我正在用几个c#正则表达式清理它们。让我困惑的一个问题是,文本中有许多“\r\n”字符串,实际字符不是换行符 我试过: content = Regex.Replace(content, "\\r\\n", ""); 以及: 但两者都不起作用。最后,我不得不使用: content = content.Replace("\\r\\n", "\r\n"); 完成项目,但无法在正则表达式中完成,这让我很恼火。这里的猜测: var bslash = System.IO.Path.D
content = Regex.Replace(content, "\\r\\n", "");
以及:
但两者都不起作用。最后,我不得不使用:
content = content.Replace("\\r\\n", "\r\n");
完成项目,但无法在正则表达式中完成,这让我很恼火。这里的猜测:
var bslash = System.IO.Path.DirectorySeparatorChar.ToString();
content = content.Replace(bslash + "r" + bslash + "n", "");
在用C#编写正则表达式时,养成使用逐字字符串文本(
@“example”
)的习惯是一个好主意。在这种情况下,您需要:
content = Regex.Replace(content, @"\\r\\n", "\r\n");
否则,每个反斜杠必须转义两次:一次在C#字符串中转义,然后第二次在正则表达式中转义。因此,一个反斜杠将变成四个带有标准字符串文字的反斜杠。
\r
,和\n
在正则表达式中也有特殊含义,因此反斜杠需要转义。然后,需要为c#字符串转义这些反斜杠,从而导致
content = Regex.Replace(content, "\\\\r\\\\n", "");
或
可能有用。更多信息
引述:
在文本C#字符串中,以及在
C++和许多其他.NET语言,
反斜杠是转义字符。这个
文字字符串“\\”是单个
反斜杠。在正则表达式中
反斜杠也是转义字符。
正则表达式\\与
单反斜杠。这个常客
作为C#字符串的表达式变为
"\\\\". 没错:4个反斜杠
匹配一个
注意:我必须在下一句的最后一句中写8个反斜杠,这样就可以显示4个反斜杠;-) 在指定的输入字符串中,
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);
这似乎不是你想要做的。这个问题很老了,但已经有了变化
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应用程序,也可能适用于其他应用程序。这里有一个更好、更简单的答案。它对我使用正则表达式有效
public static string GetMultilineBreak(this string content)
{
return Regex.Replace(content, @"\r\n?|\n", "<br>");
}
public静态字符串getmultilebreak(此字符串内容)
{
返回Regex.Replace(内容,@“\r\n?|\n”,“
”;
}
这有帮助吗?内容。替换(@“\r\n”,“\r\n”)是您最好的选择。@Jens:当然。我想说的是,对于这样一个琐碎的任务,使用正则表达式是最好的选择,而且要好得多
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
public static string GetMultilineBreak(this string content)
{
return Regex.Replace(content, @"\r\n?|\n", "<br>");
}