You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA网页抓取:如何将含[STM]标识的字符串拆分存入数组?

VBA: Split Dynamic Error String into Array Based on Pattern

Got it, let's break down how to split your target string into the desired array in VBA. The key here is recognizing the repeating pattern in your string: each valid substring starts with one or more digits, followed by [STM], and continues until the next set of leading digits (or the end of the string).

Regex is perfect here because it can dynamically match the repeating pattern regardless of how many substrings you have. You can use late binding (no library reference needed) for broader compatibility:

Sub SplitErrorStringIntoArray()
    ' Your input string
    Dim inputStr As String
    inputStr = "123434[STM]CompilationError_Lib.c23434[STM]LinkingError432122[STM]Null Pointer Exception"
    
    ' Initialize regex object
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")
    regex.Global = True ' Match all occurrences, not just the first
    
    ' Regex pattern breakdown:
    ' \d+          : Match one or more leading digits
    ' \[STM\]      : Match the literal [STM] (escape brackets since they're regex special chars)
    ' .*?          : Non-greedily match any characters (stops at the next valid pattern start)
    ' (?=\d+\[STM\]|$) : Positive lookahead to stop at either the next digit+[STM] or end of string
    regex.Pattern = "\d+\[STM\].*?(?=\d+\[STM\]|$)"
    
    ' Execute the regex to get all matches
    Dim matches As Object
    Set matches = regex.Execute(inputStr)
    
    ' Convert matches to an array
    Dim resultArr() As String
    ReDim resultArr(0 To matches.Count - 1)
    
    Dim i As Integer
    For i = 0 To matches.Count - 1
        resultArr(i) = matches(i).Value
    Next i
    
    ' Example: Print array to Immediate Window (Ctrl+G to view)
    For i = LBound(resultArr) To UBound(resultArr)
        Debug.Print "arr(" & i & ") = " & resultArr(i)
    Next i
End Sub

How It Works

  • The regex pattern dynamically identifies each valid substring without needing hardcoded positions.
  • Non-greedy matching (.*?) ensures we don't accidentally capture multiple substrings in one match.
  • The positive lookahead ((?=...)) acts as a "stop signal" for each match, ensuring we split exactly where the next substring starts.

Solution 2: Manual String Parsing (No Regex)

If you prefer to avoid regex, you can loop through the string to find each split point. This is more verbose but works if regex feels overkill:

Sub ManualSplitErrorString()
    Dim inputStr As String
    inputStr = "123434[STM]CompilationError_Lib.c23434[STM]LinkingError432122[STM]Null Pointer Exception"
    
    Dim resultArr As Collection
    Set resultArr = New Collection
    
    Dim currentPos As Integer
    currentPos = 1
    
    Do While currentPos <= Len(inputStr)
        ' Find the next [STM] starting from current position
        Dim stmPos As Integer
        stmPos = InStr(currentPos, inputStr, "[STM]")
        
        If stmPos = 0 Then Exit Do ' No more [STM] found
        
        ' Find the next starting digit after this [STM]
        Dim nextDigitPos As Integer
        nextDigitPos = stmPos + 4 ' Start searching after [STM] (length 4)
        
        Do While nextDigitPos <= Len(inputStr)
            If IsNumeric(Mid(inputStr, nextDigitPos, 1)) Then
                Exit Do
            End If
            nextDigitPos = nextDigitPos + 1
        Loop
        
        ' Extract the substring: from currentPos to either nextDigitPos-1 or end of string
        Dim substring As String
        If nextDigitPos > Len(inputStr) Then
            substring = Mid(inputStr, currentPos)
        Else
            substring = Mid(inputStr, currentPos, nextDigitPos - currentPos)
        End If
        
        resultArr.Add substring
        currentPos = nextDigitPos
    Loop
    
    ' Convert collection to array (if you need an array instead of collection)
    Dim arr() As String
    ReDim arr(0 To resultArr.Count - 1)
    For i = 1 To resultArr.Count
        arr(i - 1) = resultArr(i)
    Next i
    
    ' Example output
    For i = LBound(arr) To UBound(arr)
        Debug.Print "arr(" & i & ") = " & arr(i)
    Next i
End Sub

Notes

  • Both solutions handle a variable number of substrings, so you don't need to predefine the array size upfront.
  • The regex method is more maintainable if your pattern ever changes (e.g., different delimiters), while the manual method avoids relying on external regex libraries.

内容的提问来源于stack exchange,提问作者Gopala Krishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:32:31