替換在正則表達式查找中找到的文本。
object.Replace(string1, string2)
被替換的文本的實際模式是通過 RegExp 對象的 Pattern 屬性設(shè)置的。
Replace 方法返回 string1 的副本,其中的 RegExp.Pattern 文本已經(jīng)被替換為 string2。如果沒有找到匹配的文本,將返回原來的 string1 的副本。
下面的例子說明了 Replace 方法的用法。
Function ReplaceTest(patrn, replStr) Dim regEx, str1 ' 建立變量。 str1 = "The quick brown fox jumped over the lazy dog." Set regEx = New RegExp ' 建立正則表達式。 regEx.Pattern = patrn ' 設(shè)置模式。 regEx.IgnoreCase = True ' 設(shè)置是否區(qū)分大小寫。 ReplaceTest =regEx.Replace(
str1,
replStr)
' 作替換。 End Function MsgBox(ReplaceTest("fox", "cat")) ' 將 'fox' 替換為 'cat'。
;另外,Replace 方法在模式中替換 subexpressions 。下面對以前示例中函數(shù)的調(diào)用,替換了原字符串中的所有字對:
MsgBox(ReplaceText("(\S+)(\s+)(\S+)", "$3$2$1")) ' 交換詞對.
應(yīng)用于:RegExp 對象