RegExp 对象中的 Replace 方法用于在字符串中搜索模式,并将其替换为指定的替换字符串。
语法:RegExpObject.Replace(string, replacement)
参数:
string:将在其中进行搜索和替换的输入字符串。
replacement:将替换匹配模式的字符串。这还可以包括特殊的替换令牌(如 $1、$2 等),以引用正则表达式中捕获的组。
示例 1:简单替换
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."
示例 2:在替换中使用捕获组
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."