日期:2012-11-24  浏览次数:20832 次

被替换的文本的实际模式是通过 RegExp 对象的 Pattern 属性设置的。

Replace 方法返回 string1 的副本,其中的 RegExp.Pattern 文本已经被替换为 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 ' 设置模式。
regEx.IgnoreCase = True ' 设置是否区分大小写。
ReplaceTest = regEx.Replace(str1, replStr) ' 作替换。
End Function

MsgBox(ReplaceTest("fox", "cat")) ' 将 'fox' 替换为 'cat'。
;另外,Replace 方法在模式中替换 subexpressions 。 下面对以前示例中函数的调用,替换了原字符串中的所有字
对:

MsgBox(ReplaceText("(\S+)(\s+)(\S+)", "$3$2$1")) ' 交换词对.

要求的脚本语言在5.0以上