つらつら Excel VBA

私の備忘録です。

正規表現でひらがなを検出したい

'参照設定
'Microsoft VBScript Regular Expressions 5.5

Sub 正規表現テスト()
    
    Dim RE As New RegExp
    'Set RE = CreateObject("VBScript.RegExp")
    Dim Matches, Match
    Dim strPattern As String
    
    Dim r As Range
    
    strPattern = "[ぁ-ん]"         'ひらがな比較
    'strPattern = "[一-龠〃々〆〇]" '漢字比較
    'strPattern = "[ァ-ヶ]"         '全角カタカナ比較
    'strPattern = "[。-゚]"           '半角カタカナ比較
    'strPattern = "[^ぁ-んァ-ヶ一-龠〃々〆〇。-゚]" '日本語以外比較
    
    With RE
        .Pattern = strPattern       '検索パターンを設定
        .IgnoreCase = False         '大文字と小文字を区別する(False)、しない(True)
        .Global = True              '文字列全体を検索する(True)、しない(False)
        For Each r In Range("A1:E30")
            Set Matches = .Execute(r.Value)
            If Matches.Count > 0 Then
                Debug.Print r.Value
                For Each Match In Matches
                    Debug.Print Match.Value & " " & (Match.FirstIndex + 1) & "文字目"
                Next
            End If
        Next
    End With
    Set RE = Nothing
End Sub