VBAで正規表現を使う方法

広告

広告

解説

Microsoft VBScript Regular Expressions 5.5 の参照設定をOnにしなければならない。

ソース

Dim arrbuf() As String
arrbuf = Split(buf, "@")
For Each buf2 In arrbuf
    Dim myRegExp          As RegExp
    Dim myMatchCollection As MatchCollection

    Set myRegExp = New RegExp
    myRegExp.Pattern = "([A-Z]{1})([A-Z]{2}\d{4}|\d{6,7})"
    myRegExp.Global = True 'マッチしたものは全て格納
    myRegExp.IgnoreCase = True '大文字小文字の区別なし

    Set myMatchCollection = myRegExp.Execute(buf2)

    For Each myMatch In myMatchCollection
        Set MySubMatches = myMatch.SubMatches
        If MySubMatches.Count = 2 Then
            MsgBox MySubMatches.Item(0)'$1に相当する値
            MsgBox MySubMatches.Item(1)'$2に相当する値
        End If
    Next

    Set myMatchCollection = Nothing
    Set myRegExp = Nothing
Next

広告

Copyright (C) 2006 七鍵 key@do.ai 初版:2006年08月28日 最終更新:2006年08月28日