第一种方式(需要引用VBScript RegularExpression 5.5类库)
Option Explicit Sub RegularExpresstion()'方法块 Dim regex AS New RegExp '绑定定义对象 With regex .Global=True '匹配多次 .IgnoreCase=False '区分大小写 .Pattern="([0-9]+)-([0-9]+)[a-zA-Z]+" '正则表达式 End With Dim m As Match 'Match对象 Dim mc as MatchCollection 'Match集合
Dim i as Integer
With Thisworkbook.Worksheets("Sheet1")
For i= To .Range("A65536").End(xlUp).Row
Set mc =regex.Execute(.Range("A" & i) '执行
'提取组 和C#有所区别(第一组不是全部表达式而是第一个圆括号内的内容)
'索引位置用SubMatches()方法,而不是Group[]
For Each m In mc
.Range("B" & i).Value=m.SubMatches()
.Range("C" & i).Value=m.SubMatches()
Next
Next
End With
End Sub
第二种方式(无需直接引用类库,创建新实例)
Option Explicit
Sub RegularExpression()
Dim reg As Object
Dim mc As Object 'Matchcollection
Dim m As Object 'Match
Set reg = CreateObject("VbScript.regexp") '创建正则项目
With reg
.Global =True '匹配多次
.IgnoreCase = False '匹配大小写
.Pattern = "[0-9A-Z]+" 正则表达式
End With
Set mc=reg.Execute(Range("E7")) '执行语句
For Each m In mc '遍历
MsgBox m
Next
End Sub