C# 正则表达式替换 \n

3

我正在尝试删除 [/quote] 后的任何换行符。

目前我的代码如下:

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

但它似乎没有起到任何作用!

示例:

[/quote]


hey nice quote blah blah

前往
[/quote]hey nice quote blah blah
4个回答

3
你确定你的字符串以UNIX风格的换行符\n结尾,而不是Windows风格的换行符\r\n吗?
此外,请注意,在正则表达式中,[...]表示字符类,因此你的[/quote]匹配一个字符,它可以是/quote。你必须将[转义为\[来匹配一个开括号字符。
将它们组合在一起(并将{1,}简化为简写形式+),然后尝试这个:
Regex.Replace(Comment, @"\[/quote\][\r\n]+", "[/quote]");

太棒了,谢谢!那么 [\r\n] 匹配其中任何一个吗? - Tom Gullen
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\r\r\n\r\n\n\n\r等。 - Callum Rogers

0
在编程中,添加一个“+”符号来匹配所有的“\n”。

0

你还需要转义换行符 [/quote][\\n]+


0

尝试使用这个正则表达式

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接