Visual Basic .NET find blank lines

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

You can use this recipe for identifying blank lines in a file. Blank lines can contain spaces or tabs, or they can contain a combination of spaces and tabs. Variations on these expressions can be useful for stripping blank lines from a file.

[edit] code

Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Recipe
    Private Shared _Regex As Regex = New Regex("^\s*$")
    Public Sub Run(ByVal fileName As String)
        Dim line As String
        Dim lineNbr As Integer = 0
        Dim sr As StreamReader = File.OpenText(fileName)
        line = sr.ReadLine
        While Not line Is Nothing
            lineNbr = lineNbr + 1
            If _Regex.IsMatch(line) Then
                Console.WriteLine("Found match '{0}' at line {1}", _
                    line, _
                    lineNbr)
            End If
            line = sr.ReadLine
        End While
        sr.Close()
    End Sub
    Public Shared Sub Main(ByVal args As String())
        Dim r As Recipe = New Recipe
        r.Run(args(0))
    End Sub
End Class

[edit] How It Works

In addition to completely blank lines, this expression also matches lines that have only tabs or spaces in them. It does this by using the \s character class, which matches a tab or a space.

    Here's the expression broken down into parts:
Regular Expression Description
^ starts the beginning of the line, followed by . . .
\s any whitespace character (a tab or space) . . .
* zero or more times, followed by . . .
$ the end of the line.
Personal tools