如何从格式化字符串中删除空行
如何删除 C# 中字符串中的空行?
我正在用 C#(Windows 窗体)生成一些文本文件,由于某种原因有一些空行。如何在生成字符串后删除它们(使用 StringBuilder 和 TextWrite)。
文本文件示例:
THIS IS A LINE
THIS IS ANOTHER LINE AFTER SOME EMPTY LINES!
How can I remove empty lines in a string in C#?
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).
Example text file:
THIS IS A LINE
THIS IS ANOTHER LINE AFTER SOME EMPTY LINES!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
如果您还想删除仅包含空格的行,请使用
^\s+$
将删除从第一个空行到最后一个空行(在连续的空行块中)的所有内容,包括仅包含空格的行制表符或空格。然后,
[\r\n]*
将删除最后一个 CRLF(或只是 LF,这很重要,因为 .NET 正则表达式引擎会匹配\r 之间的
和一个$
\n
,有趣的是)。If you also want to remove lines that only contain whitespace, use
^\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]*
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).Tim Pietzcker - 它不适用于我。我必须稍微改变一下,但是谢谢!
呃 C# Regex ..我不得不再次更改它,但这运行良好:
示例:
http://regex101.com/r/vE5mP1/2
Tim Pietzcker - it is not working for me. I have to change a little bit, but thanks!
Ehhh C# Regex.. I had to change it again, but this it working well:
Example:
http://regex101.com/r/vE5mP1/2
您可以尝试
String.Replace("\n\n", "\n");
You could try
String.Replace("\n\n", "\n");
试试这个
Try this
我找到了这个问题的简单答案:
改编自 Marco Minerva [MCPD] at 删除行来自多行文本框(如果它包含特定字符串) - C#
I found a simple answer to this problem:
Adapted from Marco Minerva [MCPD] at Delete Lines from multiline textbox if it's contain certain string - C#
这里提到的方法都没有对我有帮助,但我找到了解决方法。
将文本拆分为行 - 字符串集合(带或不带空字符串,还有每个字符串Trim())。
将这些行添加到多行字符串中。
None of the methods mentioned here helped me all the way, but I found a workaround.
Split text to lines - collection of strings (with or without empty strings, also Trim() each string).
Add these lines to multiline string.
基于 Evgeny Sobolev 的代码,我编写了这个扩展方法,它还使用 TrimEnd(TrimNewLineChars) 修剪最后一个(过时的)换行符:
Based on Evgeny Sobolev's code, I wrote this extension method, which also trims the last (obsolete) line break using TrimEnd(TrimNewLineChars):
我尝试了以前的答案,但其中一些正则表达式无法正常工作。
如果您使用正则表达式来查找空行,则无法使用相同的方法进行删除。
因为它会删除非空行的“断行”。
您必须使用“正则表达式组”来进行此替换。
其他一些没有正则表达式的答案可能会出现性能问题。
I tried the previous answers, but some of them with regex do not work right.
If you use a regex to find the empty lines, you can’t use the same for deleting.
Because it will erase "break lines" of lines that are not empty.
You have to use "regex groups" for this replace.
Some others answers here without regex can have performance issues.
此模式非常适合删除空行以及仅包含空格和/或制表符的行。
This pattern works perfect to remove empty lines and lines with only spaces and/or tabs.