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