从字符串有效地去除所有空白 [英] Removing all whitespace from a string efficiently

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

问题描述

在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);



Edit(对于@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天全站免登陆