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.
On Error Resume Next
Set RegEx = New RegExp ' Create regular expression.
RegEx.IgnoreCase = True ' Make case insensitive.
RegEx.Global=True 'Search the entire String
If RegEx.Test(strString) Then 'Test if match is made
RegExReplace = regEx.Replace(strString, strReplace) ' Make replacement.
'return original string
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'"
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.