Il metodo Replace nell'oggetto RegExp viene utilizzato per cercare un pattern in una stringa e sostituirlo con una stringa di sostituzione specificata.
Sintassi: RegExpObject.Replace(string, replacement)
Argomenti:
stringa: stringa di input in cui verrà eseguita la ricerca e la sostituzione.
replacement: stringa che sostituirà i pattern corrispondenti. Sono inclusi token di sostituzione speciali, ad esempio $1, $2 e così via, per fare riferimento ai gruppi acquisiti nell'espressione regolare.
Esempio 1: sostituzione semplice
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."
Esempio 2: uso dell'acquisizione di gruppi nella sostituzione
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."