VBAで正規表現を利用する
VBAでも正規表現は利用することができる。
標準の機能としては取り込まれていないがMicrosoft VBScript Regular Expressions 5.5に機能があるのでこれを利用する。
Microsoft VBScript Regular Expressions 5.5を利用するには静的バインドと動的バインドがある。
どちらを使用しても問題ないが静的バインドを使うとVBAの入力支援が受けられるというメリットがある。
静的バインドのためにはあらかじめ参照設定をしておかなくてはならない
静的バインドの設定
VBAIDEのメニューから/ツール/参照設定 を選択し
Microsoft VBScript Regular Expressions 5.5をチェックする。
静的バインド
Dim re As New RegExp
動的バイト
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
VBAの正規表現オブジェクト
VBAの正規表現オブジェクトは以下の4つで構成される
- RegExp (正規表現文字列を表す)
- MatchCollection (ヒット文字列の集合)
- Match (個々のヒット文字列)
- SubMatches (部分文字列)
MatchCollection はグローバル指定したときの複数のヒット文字列を表す。
Matchは個々のヒット文字列を表す。
SubMatches は()で囲まれた部分文字列を表す。
RegExp のメソッド
- Execute (検索実行)
- Replace (置換実行)
- Test (一致テスト)
Testは検索文字列が存在するかどうかをテストする簡易版。
Testの使用例
Sub test()
'Microsoft VBScript Regular Expressions 5.5
Dim re As New regexp
re.Global = True
re.IgnoreCase = True
re.Pattern = "c.ndy"
r
For i = 1 To 5
If re.test(Cells(i, 1)) Then
Debug.Print "ok"
Else
Debug.Print "ng"
End If
Next
End Sub
Replaceの使用例
Sub replace()
'Microsoft VBScript Regular Expressions 5.5
Dim re As New regexp
re.Global = True
re.IgnoreCase = True
re.Pattern = "candy"
For i = 1 To 5
Debug.Print re.replace(Cells(i, 1), "aaa")
Next
End Sub
execute/Matchの使用例
Sub execute_match()
'Microsoft VBScript Regular Expressions 5.5
Dim re As New regexp
re.Global = True
re.IgnoreCase = True
re.Pattern = "(c..)(dy)"
For i = 1 To 1
Dim mc As MatchCollection
Set mc = re.Execute("Candyxxcandyxxxxcandy")
Dim m As match
For Each m In mc
Debug.Print m.FirstIndex
Debug.Print m.Length
' Debug.Print m.SubMatches
Debug.Print m.Value
Next
Next
End Sub
execute/Submatchの使用例
Sub execute_match_submatch()
'Microsoft VBScript Regular Expressions 5.5
Dim re As New regexp
re.Global = True
re.IgnoreCase = True
re.Pattern = "(c..)(dy)"
For i = 1 To 1
Dim mc As MatchCollection
Set mc = re.Execute("Candyxxcandyxxxxcandy")
Dim m As match
For Each m In mc
Debug.Print m.FirstIndex
Debug.Print m.Length
Debug.Print m.SubMatches.Count
For j = 0 To m.SubMatches.Count - 1
Debug.Print m.SubMatches(j)
Next
Debug.Print m.Value
Next
Next
End Sub