VBScript 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

Dim fso,s,re,line,lineNbr
Set fso = CreateObject("Scripting.FileSystemObject")
Set s = fso.OpenTextFile(WScript.Arguments.Item(0), 1, True)
Set re = New RegExp
re.Pattern = "^Moo\b"
lineNbr = 0
Do While Not s.AtEndOfStream
     line = s.ReadLine()
     lineNbr = lineNbr + 1
     If re.Test(line) Then
         WScript.Echo "Found match: '" & line & "' at line " & lineNbr
     End If
Loop
s.Close

[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