hakeの日記

Windows環境でプログラミングの勉強をしています。

EXCEL VBAメモ - 正規表現

Sub foo()
    Dim re As Object
    Dim str As String
    Set re = CreateObject("VBScript.RegExp")
    str = "apple"
    With re
        .Pattern = "ap"             '検索パターンを設定
        .IgnoreCase = True          '大文字と小文字を区別しない
        .Global = True              '文字列全体を検索
        If .test(str) Then
            MsgBox "マッチしました。"
        Else
            MsgBox "マッチしません。"
        End If
        str = .Replace(str, "Ap")   'マッチした文字の置換
        MsgBox str                  '-> Apple
    End With
    
    Dim ms As Object
    Dim m As Object
    With re
        .Pattern = ".."
        .IgnoreCase = True
        .Global = True
        Set ms = .Execute(str)      'Matchesコレクション
        MsgBox ms.Count              '-> 2
        For Each m In ms            'Matchオブジェクト
            MsgBox "idx = " & m.FirstIndex & vbCrLf _
                 & "size = " & m.Length & vbCrLf _
                 & "val = " & m.Value
                                    '-> idx = 0, size = 2, val = Ap
                                    '-> idx = 2, size = 2, val = pl
        Next
    End With

    
    With re
        .Pattern = "A(..)(..)"
        .IgnoreCase = True
        .Global = True
        Set ms = .Execute(str)      'Matchesコレクション
        MsgBox ms.Count             '-> 1
        Set m = ms(0)               'Matchオブジェクト
        MsgBox "idx = " & m.FirstIndex & vbCrLf _
                 & "size = " & m.Length & vbCrLf _
                 & "val = " & m.Value
                                    '-> idx = 0, size = 5, val = Apple
        MsgBox m.SubMatches.Count   '-> 2
        For i = 0 To m.SubMatches.Count - 1
            MsgBox "SubMatch(" & i & ") = " & m.SubMatches(i)
        Next
                                    '-> SubMatch(0) = pp
                                    '-> SubMatch(1) = le
    End With

    Set re = Nothing
    Set ms = Nothing
    Set m = Nothing
End Sub