Visual Basic .NET Search for Lines Beginning with a Word

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

This recipe allows you to find whole words at the beginning of a line.

[edit] code

Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Recipe
    Private Shared _Regex As Regex = New Regex("^Moo\b")
    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

The key to this expression is the line anchor metacharacter ^. You can break the expression down like this:

Regular Expression Description
^ at the start of the line, followed immediately by . . .
W then . . .
o followed by . . .
r then . . .
d and lastly . . .
\b a word boundary.

The \b character class is an anchor like the ^ line anchor. However, \b is a word anchor, and the ^ metacharacter is a line anchor.

Personal tools