VBScript Simple Regex Replace

Last week I talked about using Regular Expressions in VBScript. In that post I focused on simple matching. However, you can also do string replacements using the regular expression object’s Replace() method. You specify a string to replace and its replacement text. I always test the expression to make sure the string exists before doing anything. Here’s a function I use for this task.

Function RegExReplace(strString,strPattern,strReplace)
On Error Resume Next
    Dim RegEx
    Set RegEx = New RegExp                ' Create regular expression.
    RegEx.IgnoreCase = True                ' Make case insensitive.
    RegEx.Global=True                   'Search the entire String
    RegEx.Pattern=strPattern
        
    If RegEx.Test(strString) Then       'Test if match is made
        RegExReplace = regEx.Replace(strString, strReplace)    ' Make replacement.
     Else
         'return original string   
         RegExReplace=strString
    End If
End Function

Using the functions from my earlier post it is very simple to make global changes.

strString="'The quick brown dog jumped over the lazy fox'"
strPattern="dog"
strReplace="cat"
 
strRevised=RegExReplace(strString,strPattern,strReplace)
 
WScript.Echo strString & " is now " & strRevised

“Dog” is replaced with “Cat” in this very simple example.  I’ll be back later with a more complex example.

In the meantime you can download the sample code here.