仅替换一个换行符替换多个换行符

时间:2013-03-28 07:09:24

标签: c# regex

我想在C#中只用\r\n替换任意数量的\r\n\r\n。对不起,如果这是一个愚蠢的问题,但我是regex的新手 其实我试过

clearstring = Regex.Replace(clearstring, @"\r\n+", "\r\n\r\n", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);

但它没有用,有什么建议吗?我将不胜感激。

2 个答案:

答案 0 :(得分:5)

尝试

clearstring = Regex.Replace(clearstring, @"(\r\n)+", "\r\n\r\n", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);

规则是量词(在你的情况下为加号)仅适用于前面的组或字符类,在你的情况下只有\ n。如果要包含多个字符或类,则应将它们分组为paranthesis。

答案 1 :(得分:2)

Regex.Replace(str, @"(\r\n){2,}", Environment.NewLine)

仅当找到两个或多个连续的空行时才会替换

相关问题