正则表达式(RegExp)对象 说明
Function
RegExpTest(patrn, strng)
Dim regEx, Match, Matches ' 建立变量。 Set regEx = New RegExp ' 建立正则表达式。 regEx.Pattern = patrn ' 设置模式。 regEx.IgnoreCase = True ' 设置是否区分字符大小写。 regEx.Global = True ' 设置全局可用性。 Set Matches = regEx.Execute(strng) ' 执行搜索。 For Each Match in Matches ' 遍历匹配集合。 RetStr = RetStr & " Match found at position " RetStr = RetStr & Match.FirstIndex & " . Match Value is ' " RetStr = RetStr & Match.Value & " '. " & vbCRLF Next RegExpTest = RetStr End Function MsgBox (RegExpTest( " is. " , " IS1 is2 IS3 is4 " )) Global 属性 object.Global [= True | False ] 对象 参数总是 RegExp 对象。如果搜索应用于整个字符串,Global 属性的值为 True,否则其值为 False。默认的设置为 False。 IgnoreCase 属性 object.IgnoreCase [= True | False ] Object 参数总是一个 RegExp 对象。如果搜索是区分大小写的,则 IgnoreCase 属性为 False;否则为 True。缺省值为 False。 Pattern 属性 设置或返回被搜索的正则表达式模式。 object.Pattern [= "searchstring"] 参数 object 必选项。总是一个 RegExp 对象变量。 searchstring 可选项的。被搜索的正则字符串表达式。它可能包含设置部分表格中的各种正则表达式字符。 Execute 方法 object.Execute(string) 参数 必选项。总是一个 RegExp 对象的名称。 string 必选项。要在其上执行正则表达式的文本字符串。 说明 Execute 方法返回一个 Matches 集合,其中包含了在 string 中找到的每一个匹配的 Match 对象。如果未找到匹配,Execute 将返回空的 Matches 集合。 Replace 方法 object.Replace(string1, string2) 参数 必选项。总是一个 RegExp 对象的名称。 string1 必选项。string1 是将要进行文本替换的字符串。 string2 必选项。 string2 是替换文本字符串。 说明 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 FunctionMsgBox(ReplaceTest( " fox " , " cat " )) ' 将 'fox' 替换为 'cat'。 ;另外, Replace 方法在模式中替换 subexpressions 。 下面对以前示例中函数的调用,替换了原字符串中的所有字对: MsgBox (ReplaceText( " (/S+)(/s+)(/S+) " , " $3$2$1 " )) ' 交换词对. Test 方法 object.Test(string) 参数 必选项。总是一个 RegExp 对象的名称。 string 必选项。要执行正则表达式搜索的文本字符串。 说明 如果找到了匹配的模式,Test方法返回True;否则返回False。 下面的代码说明了Test 方法的用法。
Function
RegExpTest(patrn, strng)
Dim regEx, retVal ' 建立变量。 Set regEx = New RegExp ' 建立正则表达式。 regEx.Pattern = patrn ' 设置模式。 regEx.IgnoreCase = False ' 设置是否区分大小写。 retVal = regEx.Test(strng) ' 执行搜索测试。 If retVal Then RegExpTest = " 找到一个或多个匹配。 " Else RegExpTest = " 未找到匹配。 " End If End Function MsgBox (RegExpTest( " is. " , " IS1 is2 IS3 is4 " )) |