0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBAで正規表現で部分文字列を取得する

Posted at

VBAで部分文字列を取得するには

単純に正規表現文字列と一致するかどうかはTest()を使えばいい。
一致文字列を取得するにはExecute() からmatchを取得しValueを取得すればいい。
では部分文字列はどのようにして取得するか。

VBAのregexpは汎用的にできているので暗黙裡に繰り返しのパターンマッチ、部分マッチを処理するようにできている。
1回だけマッチしたい場合は繰り返しは必要ない。

Sub get_sub_match()
    'Microsoft VBScript Regular Expressions 5.5
    Dim re As New regexp
    
    re.Global = True
    re.IgnoreCase = True
    re.Pattern = "(c...y)[^0-9]+([0-9]+)"
    
    Dim mc As MatchCollection
    Set mc = re.Execute("don't tell me you love me candy for 777times")
    If mc.Count <> 0 Then
        Dim m As match
        Set m = mc.Item(0)
            
        Debug.Print "FirstIndex = "; m.FirstIndex
        Debug.Print "Length = "; m.Length
        Debug.Print "SubMatches.Count = "; m.SubMatches.Count
        Dim j As Integer
        For j = 0 To m.SubMatches.Count - 1
            Debug.Print "SubMatches = "; m.SubMatches(j)
        Next
        Debug.Print "Value = "; m.Value
    Else
        Debug.Print "not matched."
    End If
End Sub

結果は以下のようになる。
期待通りの部分文字列1と2を得ることができた。

FirstIndex =  26 
Length =  13 
SubMatches.Count =  2 
SubMatches = candy
SubMatches = 777
Value = candy for 777
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?