【发布时间】:2012-08-31 18:11:20
【问题描述】:
我有一些类似的文字
This is a line
This is other line
This is another line
如何去掉那些多空行?
我想要的是
This is a line
This is other line
This is another line
\s 表示匹配任何空白字符(空格、制表符、换行符),但我不知道如何将多个空行变为一个空行?
【问题讨论】:
我有一些类似的文字
This is a line
This is other line
This is another line
如何去掉那些多空行?
我想要的是
This is a line
This is other line
This is another line
\s 表示匹配任何空白字符(空格、制表符、换行符),但我不知道如何将多个空行变为一个空行?
【问题讨论】:
Regex.Replace(input, @"(\r?\n\s*){2,}", Environment.NewLine + Environment.NewLine);
\r 是可选的,它可以与 Unix 风格的行终止符一起使用。不过,输出将具有 Windows 样式的终止符。
\s* 允许它匹配包含空格的行。 (我最初在此处输入了 ? 以使匹配不贪婪,但这实际上不是必需的,在这种情况下可能是有害的。在 .NET 正则表达式中,\s 和 . 不匹配换行符默认RegexOptions。)
{2,} 确保它只匹配两个仅由空格分隔的连续换行符。
【讨论】: