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