如何从格式化的字符串中删除空行? [英] How to remove empty lines from a formatted string?

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

问题描述

如何删除空行,在C#中的字符串?我生成一些文本文件在C#(的WinForms),并由于某种原因,也有一些空行。我怎样才能删除它们生成后的字符串(使用 StringBuilder的和<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/system.io.textwriter.aspx> TextWrite )。

How to remove empty lines in a string in C#? I am generating some text files in C# (winforms) and for some reason there are some empty lines. How can I remove them after the string is generated (using StringBuilder and TextWrite).

例如文本文件:

THIS IS A LINE



THIS IS ANOTHER LINE AFTER SOME EMPTY LINES!

感谢。

推荐答案

如果你也想删除只包含空格,用线

If you also want to remove lines that only contain whitespace, use

resultString = Regex.Replace(subjectString, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);

^ \\ S + $ 将删除一切从第一个空行到最后(在空行的邻接块),其中仅包含制表符或空格线。

^\s+$ will remove everything from the first blank line to the last (in a contiguous block of empty lines), including lines that only contain tabs or spaces.

[\\ r \\ n] * 然后将删除最后一个CRLF(或只是LF这一点很重要,因为.NET正则表达式引擎匹配 $ A 之间\\ r \\ n ,有趣的是)。

[\r\n]* will then remove the last CRLF (or just LF which is important because the .NET regex engine matches the $ between a \r and a \n, funnily enough).

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

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