您的位置:首页 > 其它

正则表达式RegExp对象的方法

2010-01-16 14:53 267 查看
1. Execute方法
说明:Execute方法对指定的字符串执行正则表达式搜索。正则表达式搜索的设计模式是通过 RegExp 对象的 Pattern 来设置的。Execute 方法返回一个 Matches 集合,其中包含了在 string 中找到的每一个匹配的 Match 对象。如果未找到匹配,Execute 将返回空的 Matches 集合。
语法:object.Execute(string)
语法描述:
● object 必需的。总是一个 RegExp 对象的名称。
● string 必需的。要在其上执行正则表达式的文本字符串。
运用举例:
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"))
2. Replace方法
说明:Replace方法替换在正则表达式查找中找到的文本。被替换的文本的实际模式是通过 RegExp 对象的 Pattern 属性设置的。Replace 方法返回 string1 的副本,其中的 RegExp.Pattern 文本已经被替换为 string2。如果没有找到匹配的文本,将返回原来的 string1 的副本。
语法:object.Replace(string1, string2)
语法描述:
● object 必需的。总是一个 RegExp 对象的名称。
● string1 必需的。string1 是将要进行文本替换的字符串。
● string2 必需的。 string2 是替换文本字符串。
运用举例:
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"))
3. Test方法
说明:Test方法对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。正则表达式搜索的实际模式是通过RegExp对象的Pattern属性来设置的。RegExp.Global属性对Test方法没有影响。如果找到了匹配的模式,Test方法返回True;否则返回False。
语法:object.Test(string)
语法描述:
● object 必需的。总是一个 RegExp 对象的名称。
● string 必需的。要执行正则表达式搜索的文本字符串。
运用举例:
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("ow", "windowXP"))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: