如何从格式化字符串中删除空行

发布于 2024-12-08 04:58:17 字数 427 浏览 0 评论 0原文

如何删除 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

梦途 2024-12-15 04:58:17

如果您还想删除仅包含空格的行,请使用

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

^\s+$ 将删除从第一个空行到最后一个空行(在连续的空行块中)的所有内容,包括仅包含空格的行制表符或空格。

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

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

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

^\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).

吐个泡泡 2024-12-15 04:58:17

Tim Pietzcker - 它不适用于我。我必须稍微改变一下,但是谢谢!

呃 C# Regex ..我不得不再次更改它,但这运行良好:

private string RemoveEmptyLines(string lines)
{
  return Regex.Replace(lines, @"^\s*$\n|\r", string.Empty, RegexOptions.Multiline).TrimEnd();
}

示例:
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:

private string RemoveEmptyLines(string lines)
{
  return Regex.Replace(lines, @"^\s*$\n|\r", string.Empty, RegexOptions.Multiline).TrimEnd();
}

Example:
http://regex101.com/r/vE5mP1/2

扭转时空 2024-12-15 04:58:17

您可以尝试 String.Replace("\n\n", "\n");

You could try String.Replace("\n\n", "\n");

撩发小公举 2024-12-15 04:58:17

试试这个

Regex.Replace(subjectString, @"^\r?\n?$", "", RegexOptions.Multiline);

Try this

Regex.Replace(subjectString, @"^\r?\n?$", "", RegexOptions.Multiline);
佼人 2024-12-15 04:58:17
private string remove_space(string st)
{
    String final = "";

    char[] b = new char[] { '\r', '\n' };
    String[] lines = st.Split(b, StringSplitOptions.RemoveEmptyEntries);
    foreach (String s in lines)
    {
        if (!String.IsNullOrWhiteSpace(s))
        {
            final += s;
            final += Environment.NewLine;
        }
    }

    return final;
}
private string remove_space(string st)
{
    String final = "";

    char[] b = new char[] { '\r', '\n' };
    String[] lines = st.Split(b, StringSplitOptions.RemoveEmptyEntries);
    foreach (String s in lines)
    {
        if (!String.IsNullOrWhiteSpace(s))
        {
            final += s;
            final += Environment.NewLine;
        }
    }

    return final;
}
泪之魂 2024-12-15 04:58:17
private static string RemoveEmptyLines(string text)
{
    var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

    var sb = new StringBuilder(text.Length);

    foreach (var line in lines)
    {
        sb.AppendLine(line);
    }

    return sb.ToString();
}
private static string RemoveEmptyLines(string text)
{
    var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

    var sb = new StringBuilder(text.Length);

    foreach (var line in lines)
    {
        sb.AppendLine(line);
    }

    return sb.ToString();
}
森林迷了鹿 2024-12-15 04:58:17

我找到了这个问题的简单答案:

YourradTextBox.Lines = YourradTextBox.Lines.Where(p => p.Length > 0).ToArray();

改编自 Marco Minerva [MCPD] at 删除行来自多行文本框(如果它包含特定字符串) - C#

I found a simple answer to this problem:

YourradTextBox.Lines = YourradTextBox.Lines.Where(p => p.Length > 0).ToArray();

Adapted from Marco Minerva [MCPD] at Delete Lines from multiline textbox if it's contain certain string - C#

妳是的陽光 2024-12-15 04:58:17

这里提到的方法都没有对我有帮助,但我找到了解决方法。

  1. 将文本拆分为行 - 字符串集合(带或不带空字符串,还有每个字符串Trim())。

  2. 将这些行添加到多行字符串中。

     public static IEnumerable; SplitToLines(此字符串 inputText, bool removeEmptyLines = true)
     {
         如果(输入文本==空)
         {
             产量突破;
         }
    
         使用 (StringReader reader = new StringReader(inputText))
         {
             串线;
             while ((line = reader.ReadLine()) != null)
             {
                 if (removeEmptyLines && !string.IsNullOrWhiteSpace(line))
                     产量返回线.Trim();
                 别的
                     产量返回线.Trim();
             }
         }
     }
    
     公共静态字符串ToMultilineText(此字符串文本)
     {
         varlines = text.SplitToLines();
    
         return string.Join(Environment.NewLine,lines);
     }
    

None of the methods mentioned here helped me all the way, but I found a workaround.

  1. Split text to lines - collection of strings (with or without empty strings, also Trim() each string).

  2. Add these lines to multiline string.

     public static IEnumerable<string> SplitToLines(this string inputText, bool removeEmptyLines = true)
     {
         if (inputText == null)
         {
             yield break;
         }
    
         using (StringReader reader = new StringReader(inputText))
         {
             string line;
             while ((line = reader.ReadLine()) != null)
             {
                 if (removeEmptyLines && !string.IsNullOrWhiteSpace(line))
                     yield return line.Trim();
                 else
                     yield return line.Trim();
             }
         }
     }
    
     public static string ToMultilineText(this string text)
     {
         var lines = text.SplitToLines();
    
         return string.Join(Environment.NewLine, lines);
     }
    
柒七 2024-12-15 04:58:17

基于 Evgeny Sobolev 的代码,我编写了这个扩展方法,它还使用 TrimEnd(TrimNewLineChars) 修剪最后一个(过时的)换行符:

public static class StringExtensions
{
    private static readonly char[] TrimNewLineChars = Environment.NewLine.ToCharArray();

    public static string RemoveEmptyLines(this string str)
    {
        if (str == null)
        {
            return null;
        }

        var lines = str.Split(TrimNewLineChars, StringSplitOptions.RemoveEmptyEntries);

        var stringBuilder = new StringBuilder(str.Length);

        foreach (var line in lines)
        {
            stringBuilder.AppendLine(line);
        }

        return stringBuilder.ToString().TrimEnd(TrimNewLineChars);
    }
}

Based on Evgeny Sobolev's code, I wrote this extension method, which also trims the last (obsolete) line break using TrimEnd(TrimNewLineChars):

public static class StringExtensions
{
    private static readonly char[] TrimNewLineChars = Environment.NewLine.ToCharArray();

    public static string RemoveEmptyLines(this string str)
    {
        if (str == null)
        {
            return null;
        }

        var lines = str.Split(TrimNewLineChars, StringSplitOptions.RemoveEmptyEntries);

        var stringBuilder = new StringBuilder(str.Length);

        foreach (var line in lines)
        {
            stringBuilder.AppendLine(line);
        }

        return stringBuilder.ToString().TrimEnd(TrimNewLineChars);
    }
}
诺曦 2024-12-15 04:58:17

我尝试了以前的答案,但其中一些正则表达式无法正常工作。

如果您使用正则表达式来查找空行,则无法使用相同的方法进行删除。

因为它会删除非空行的“断行”。

您必须使用“正则表达式组”来进行此替换。

其他一些没有正则表达式的答案可能会出现性能问题。

    private string remove_empty_lines(string text) {
        StringBuilder text_sb = new StringBuilder(text);
        Regex rg_spaces = new Regex(@"(\r\n|\r|\n)([\s]+\r\n|[\s]+\r|[\s]+\n)");
        Match m = rg_spaces.Match(text_sb.ToString());
        while (m.Success) {
            text_sb = text_sb.Replace(m.Groups[2].Value, "");
            m = rg_spaces.Match(text_sb.ToString());
        }
        return text_sb.ToString().Trim();
    }

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.

    private string remove_empty_lines(string text) {
        StringBuilder text_sb = new StringBuilder(text);
        Regex rg_spaces = new Regex(@"(\r\n|\r|\n)([\s]+\r\n|[\s]+\r|[\s]+\n)");
        Match m = rg_spaces.Match(text_sb.ToString());
        while (m.Success) {
            text_sb = text_sb.Replace(m.Groups[2].Value, "");
            m = rg_spaces.Match(text_sb.ToString());
        }
        return text_sb.ToString().Trim();
    }
南街女流氓 2024-12-15 04:58:17

此模式非常适合删除空行以及仅包含空格和/或制表符的行。

s = Regex.Replace(s, "^\s*(\r\n|\Z)", "", RegexOptions.Multiline)

This pattern works perfect to remove empty lines and lines with only spaces and/or tabs.

s = Regex.Replace(s, "^\s*(\r\n|\Z)", "", RegexOptions.Multiline)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文