有效地从多行字符串中删除所有空格行 [英] Removing all whitespace lines from a multi-line string efficiently

查看:77
本文介绍了有效地从多行字符串中删除所有空格行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,删除空白行(即仅包含字符串中的空格的行)的最佳方法是什么?如果这是最好的解决方案,我很乐意使用正则表达式.

In C# what's the best way to remove blank lines i.e., lines that contain only whitespace from a string? I'm happy to use a Regex if that's the best solution.

我应该添加我正在使用.NET 2.0.

I should add I'm using .NET 2.0.

赏金更新:赏金获得奖励后,我会回退,但我想澄清一些事情.

Bounty update: I'll roll this back after the bounty is awarded, but I wanted to clarify a few things.

首先,任何Perl 5 compat正则表达式都可以使用.这不仅限于.NET开发人员.标题和标签已经过编辑以体现这一点.

First, any Perl 5 compat regex will work. This is not limited to .NET developers. The title and tags have been edited to reflect this.

第二,虽然我在赏金细节方面举了一个简短的例子,但这不是您必须满足的 测试.您的解决方案必须删除所有行,其中仅包含空格,以及最后一个换行符.如果有一个字符串,在通过正则表达式运行后以"/r/n"或任何空格字符结尾,则它将失败.

Second, while I gave a quick example in the bounty details, it isn't the only test you must satisfy. Your solution must remove all lines which consist of nothing but whitespace, as well as the last newline. If there is a string which, after running through your regex, ends with "/r/n" or any whitespace characters, it fails.

推荐答案

如果要删除包含任何空格(制表符,空格)的行,请尝试:

If you want to remove lines containing any whitespace (tabs, spaces), try:

string fix = Regex.Replace(original, @"^\s*$\n", string.Empty, RegexOptions.Multiline);

编辑(针对@Will):修剪尾随换行符的最简单解决方案是使用 TrimEnd 放在结果字符串上,例如:

Edit (for @Will): The simplest solution to trim trailing newlines would be to use TrimEnd on the resulting string, e.g.:

string fix =
    Regex.Replace(original, @"^\s*$\n", string.Empty, RegexOptions.Multiline)
         .TrimEnd();

这篇关于有效地从多行字符串中删除所有空格行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆