VBScript Find a Word

From Regex Regular Expression Encyclopedia

Jump to: navigation, search

You can use this recipe for finding single words in a block of text. The expression will find only complete words surrounded by spaces or other word delimiters, such as punctuation or the beginning or end of a line.

[edit] code

WORDS AND TEXT
               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 = "\bsomething\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

A special character class, \b, allows you to easily search for whole words. This is an advantage because without doing a whole bunch of extra work you can make sure that a search for some- thing, for example, doesn’t yield unexpected matches such as somethings. You can break the regular expression shown here into the following:

Regular Expression Description
\b a word boundary (a space, beginning of a line, or punctuation) . . .
something s, o, m, e, t, h, i, n, and g . . .
\b a word boundary at the end of the word.

This expression differs just slightly from the C# and Visual Basic .NET examples because the RegularExpressionValidator control assumes that the expression is to match the entire value (there’s an implied ^ at the beginning of the expression and $ at the end of the expres- sion). The combination .* has been added before and after the word boundary \b so the full word can float around inside the line.

Personal tools