How to remove empty lines from a formatted string?

后端 未结 11 1578
一生所求
一生所求 2020-12-01 02:24

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

11条回答
  •  自闭症患者
    2020-12-01 02:40

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

提交回复
热议问题