Search and Replace with Regular Expressions

There are a lot of great search and replace tools out there.  In particular I've been a fan of the tools put out by Jan Goyvaerts.  While these tools do a lot there are times where all you need is a basic search and replace with the added zest of regular expressions.  If that's what you are looking for try this VB Script:

Option Explicit
Const ForReading = 1, ForWriting = 2

If WScript.Arguments.Count <> 3 Then
    WScript.Echo "Syntax: SearchReplace.vbs   " & _
        ""
    WScript.Quit
End If

Dim fileSystemObject
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")

Dim textFile
Set textFile = fileSystemObject.OpenTextFile(WScript.Arguments(0), ForReading,
    False)

Dim fileContents
fileContents = textFile.ReadAll
textFile.Close

Dim regularExpression
Set regularExpression = New RegExp

regularExpression.IgnoreCase = True
regularExpression.Global = True
regularExpression.MultiLine = True
regularExpression.Pattern = Replace(WScript.Arguments(1), "!quot;", """")

fileContents = regularExpression.Replace(fileContents,
    Replace(WScript.Arguments(2), "!quot;", """"))

Set textFile = fileSystemObject.OpenTextFile(WScript.Arguments(0), ForWriting,
    False)
textFile.Write(fileContents)
textFile.Close

Comments Subscribe to Post Comments Feed

Be the first to share your opinion!

Have Your Say