Wednesday, December 15, 2010

RegExp object

RegExp object

VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions.

Regular Expression Object Properties and Methods:

Properties:

a) Global Property

b) IgnoreCase Property

c) Pattern Property

Methods:

a) Execute Method

b) Replace Method

c) Test Method

1) Match File Names in a Directory against Regular Expression

Set objFS = CreateObject("Scripting.FileSystemObject")

Set objShell = CreateObject("WScript.Shell")

strCurrentDirectory = objShell.CurrentDirectory

Set objFolder = objFS.GetFolder(strCurrentDirectory)

Set colFiles = objFolder.Files

Set objRE = New RegExp

objRE.Global = True

objRE.IgnoreCase = False

objRE.Pattern = WScript.Arguments(0)

For Each objFile In colFiles

bMatch = objRE.Test(objFile.Name)

If bMatch Then

WScript.Echo objFile.Name

End If

Next

2) Match Content in a File against a Regular Expression

strFileName = "E:\anand.txt"

Set objFS = CreateObject("Scripting.FileSystemObject")

Set objTS = objFS.OpenTextFile(strFileName)

strFileContents = objTS.ReadAll

WScript.Echo "Searching Within: "

WScript.Echo strFileContents

objTS.Close

Set objRE = New RegExp

objRE.Global = True

objRE.IgnoreCase = False

objRE.Pattern = WScript.Arguments(0)

Set colMatches = objRE.Execute(strFileContents)

WScript.Echo vbNewLine & "Resulting Matches:"

For Each objMatch In colMatches

WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value

Next