VB.Net – Remove blank lines from text string


To totally unlock this section you need to Log-in


Login

A simple and quick line of code, in VB.Net, to remove blank lines from a text string (or file) is to use a simple regex expression (in VB .Net):

Dim resultString As String

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

And in C#:

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

^\s+$ will remove everything (any number of spaces) 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).