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