引用了Microsoft VBScript Regular Expressions 5.5 后就可以声明正则相关对象了。主要有三个对象:RegExp、MatchCollection、Match。

RegExp对象的属性:

Global - 设置或返回一个 Boolean 值,该值指明在整个搜索字符串时模式是全部匹配还是只匹配第一个。如果搜索应用于整个字符串,Global 属性的值应该为 True,否则其值为 False。默认的设置为True。
Multiline - 返回正则表达式是否具有标志m, 缺省值为False。如果指定的搜索字符串分布在多行,这个属性是要设置为True的。
IgnoreCase - 设置或返回一个Boolean值,指明模式搜索是否区分大小写。如果搜索是区分大小写的,则 IgnoreCase 属性应该为False;否则应该设为True。缺省值为True。
Pattern - 设置或返回被搜索的正则表达式模式。 被搜索的正则字符串表达式。它包含各种正则表达式字符。

RegExp对象的方法:

Execute - 对指定的字符串执行正则表达式搜索。需要传入要在其上执行正则表达式的文本字符串。正则表达式搜索的设计模式是通过 RegExp对象的Pattern来设置的。Execute方法返回一个Matches集合,其中包含了在string中找到的每一个匹配的Match对 象。如果未找到匹配,Execute将返回空的Matches集合。
Replace - 替换在正则表达式查找中找到的文本。
Test - 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。RegExp.Global属性对Test方法没有影响。如果找到了匹配的模式,Test方法返回True;否则返回False。

MatchCollection对象与Match对象

匹配到的所有对象放在MatchCollection集合中,这个集合对象只有两个只读属性:
Count:匹配到的对象的数目
Item:集合的又一通用方法,需要传入Index值获取指定的元素。
一般,可以使用For Each语句枚举集合中的对象。集合中对象的类型是Match。

Match对象有以下几个只读的属性:

FirstIndex - 匹配字符串在整个字符串中的位置,值从0开始。
Length - 匹配字符串的长度。
Value - 匹配的字符串。
SubMatches - 集合,匹配字符串中每个分组的值。作为集合类型,有Count和Item两个属性。

例如下面的的代码:
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

示例 :

  1. RegExp的Test方法:

Function bTest(ByVal s As String, ByVal p As String) As Boolean

Dim re As RegExp

Set re = New RegExp

re.IgnoreCase = False '设置是否匹配大小写

re.Pattern = p

bTest = re.Test(s)

End Function

Private Sub Command1_Click()

Dim s As String

Dim p As String

s = "我的邮箱: test@163.com 。欢迎致电!"

'测试字符串中是否包含数字:

p = "/d+"

MsgBox bTest(s, p)

'测试字符串中是否全是由数字组成:

p = "^/d+$"

MsgBox bTest(s, p)

'测试字符串中是否有大写字母:

p = "[A-Z]+"

MsgBox bTest(s, p)

End Sub

  2. RegExp的Replace方法:

Function StrReplace(s As String, p As String, r As String) As String

Dim re As RegExp

Set re = New RegExp

re.IgnoreCase = True

re.Global = True

re.Pattern = p

StrReplace = re.Replace(s, r)

End Function

Private Sub Command2_Click()

Dim s As String '字符串

Dim p As String '正则表达式

Dim r As String '要替换的字符串

  '以下代码是替换邮箱地址

s = "我的E-mail: Test@163.com 。欢迎致电!"

p = "w+@w+.w+"

r = "E_Mail@sohu.net"

s = StrReplace(s, p, r)

Debug.Print s

'结果:我的E-mail: E_Mail@sohu.net 。欢迎致电!

End Sub

  3. Match的SubMatches属性:

Private Sub Command3_Click()

Dim re As RegExp

Dim mh As Match

Dim mhs As MatchCollection

Dim inpStr As String

inpStr = "我的E-mail: lucky@163.com 。欢迎致电!"

Set re = New RegExp

re.Pattern = "(w+)@(w+).(w+)" '同样是匹配地址,注意和上例的不同

Set mhs = re.Execute(inpStr)

Set mh = mhs(0) '只有一个匹配

Debug.Print "电子邮件地址是: " & mh.Value '这里是匹配的内容

Debug.Print "用户名是: " & mh.SubMatches(0) '第一个括号中的内容

Debug.Print "邮箱是: " & mh.SubMatches(1) '第二个括号中的内容

Debug.Print "域名是:   " & mh.SubMatches(2) '第三个括号中的内容

End Sub