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

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

问题描述

如何在 C# 中删除字符串中的空行?

How can I remove empty lines in a string in C#?

我正在用 C#(Windows 窗体)生成一些文本文件,由于某种原因,有一些空行.生成字符串后如何删除它们(使用 StringBuilderTextWrite).

I am generating some text files in C# (Windows Forms) 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]*", string.Empty, 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 正则表达式引擎匹配 $ 之间的 $>\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天全站免登陆