Monday, June 1, 2009

How to search in a text file using regular expression?

I have text file like below and I want to search all words which start with “Pass” and have number at the end. I have chosen this simple regular expression pattern in order to make you understand. You can choose any other simple or complex pattern you want to use.



Const ForReading = 1

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "Pass[0-9]"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Test.txt", ForReading)

Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
Set colMatches = objRegEx.Execute(strSearchString)
If colMatches.Count > 0 Then
For Each strMatch in colMatches
msgbox strSearchString
Next
End If
Loop

objFile.Close

Also See:
Regular Expression Object
http://www.microsoft.com/technet/scriptcenter/resources/qanda/mar07/hey0329.mspx
http://www.regular-expressions.info/vbscript.html