Search code examples
stringvbaexcelvbscriptalm

VBA Regex and String Handling


Q1 . In VBA, I am working on Web scraping and I am able to fetch the string and store into a variable. The string looks something like this:

x = "123434[STM]CompilationError_Lib.c23434[STM]LinkingError432122[STM]Null Pointer Exception"

What I want to do is, I will define an array , and store the substring into each index of the array.

arr[0] = 123434[STM]CompilationError_Lib.c

arr[1] = 23434[STM]LinkingError

arr[2] = 432122[STM]Null Pointer Exception

Caveat: There can be any number of substrings. It is not always three.

The regex pattern I have written for this is :

myRegExp.Pattern = `"\d+[:].[A-Za-z]*.[A-Za-z._]*[^0-9]"`

But it is capturing only the first substring not all the three matches.How can I do that?


Solution

  • So I will answer your first question. I suggest you split the other parts into separate questions as already mentioned in comments.

    Option Explicit
    ' Or add in Tools > References > VBScript Reg Exp for early binding
    Public Sub testing()
        Dim x As String, arr() As String, i As Long, matches As Object
        x = "123434[STM]CompilationError_Lib.c23434[STM]LinkingError432122[STM]Null Pointer Exception"
    
        Static re As Object
    
        If re Is Nothing Then
            Set re = CreateObject("VBScript.RegExp")
            re.Global = True 'Don't know how you will deploy shown here for demo
            re.MultiLine = True 'Don't know how you will deploy shown here for demo
        End If
    
        re.IgnoreCase = False
        re.Pattern = "\d+\[[a-zA-Z]{3}][^0-9]+"
        Set matches = re.Execute(x)
    
        ReDim arr(0 To matches.Count - 1)
        For i = LBound(arr) To UBound(arr)
            arr(i) = matches(i)
        Next i
    End Sub
    

    Output:

    Regex matches in array