Método Replace

O método Replace no objeto RegExp é usado para procurar um padrão em uma string e substituí-lo por uma string de substituição especificada.

Sintaxe: RegExpObject.Replace(string, replacement)

Argumentos:

  • string: A string de entrada na qual a pesquisa e a substituição ocorrerão.

  • replacement: A string que substituirá os padrões correspondentes. Isso também pode incluir tokens de substituição especiais (como $1, $2 etc.) para se referir a grupos capturados na expressão regular.

Exemplo 1: Substituição Simples

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."

Exemplo 2: Uso da Captura de Grupos na Substituição

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."