Replace Method
The Replace method in the RegExp
object is used to search for a pattern
in a string and replace it with a specified replacement string.
Syntax: RegExpObject.Replace(string, replacement)
Arguments:
-
string: The input string where the search and replace will take place.
-
replacement: The string that will replace the matched patterns. This can also include special substitution tokens (like $1, $2, etc.) to refer to captured groups in the regular expression.
Example 1: Simple Replace
Dim regEx, inputStr, result
' Create a new RegExp object
Set regEx = CreateObject("VBScript.RegExp")
' Set the pattern to match the word "cat"
regEx.IgnoreCase = True
regEx.Global = True
regEx.Pattern = "cat"
' Input string
inputStr = "The cat sat on the cat mat."
' Replace "cat" with "dog"
result = regEx.Replace(inputStr, "dog")
'Now result has the value "The dog sat on the dog mat."
Example 2: Using Capturing Groups in Replacement
Dim regEx, inputStr, result
' Create a new RegExp object
Set regEx = CreateObject("VBScript.RegExp")
' Set the pattern to match a date in MM-DD-YYYY format
regEx.IgnoreCase = True
regEx.Global = True
regEx.Pattern = "(\d{2})-(\d{2})-(\d{4})"
' Input string
inputStr = "Today's date is 05-19-2025."
' Swap the date format to YYYY-MM-DD
result = regEx.Replace(inputStr, "$3-$1-$2")
' Display the result
'Now result has the value "Today's date is 2025-05-19."