Extracting Text Between Brackets with Regex

后端 未结 4 1474
情书的邮戳
情书的邮戳 2021-01-19 12:24

In sentences like:

\"[x] Alpha

[33] Beta\"

I extract an array of bracketed data as ([x], [33])

using VBA regex Pattern:

\"(\\         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 13:11

    Use capturing around the subpatterns that will fetch you your required value.

    Use

    "\[(x)\]|\[(\d*)\]"
    

    (or \d+ if you need to match at least 1 digit, as * means zero or more occurrences, and + means one or more occurrences).

    Or, use the generic pattern to extract anything inside the square brackets without the brackets:

    "\[([^\][]+)]"
    

    Then, access the right Submatches index by checking the submatch length (since you have an alternation, either of the submatch will be empty), and there you go. Just change your for loop with

    For Each oMatch In .Execute(SourceString)
        ReDim Preserve arrMatches(lngCount)
        If Len(oMatch.SubMatches(0)) > 0 Then
            arrMatches(lngCount) = oMatch.SubMatches(0)
        Else
            arrMatches(lngCount) = oMatch.SubMatches(1)
        End If
        ' Debug.Print arrMatches(lngCount) ' - This outputs x and 33 with your data
        lngCount = lngCount + 1
    Next
    

提交回复
热议问题