excel VB regexp 5.5 捕获组

Sam*_*Man 3 regex excel vba

我在 excel 宏中使用 regexp 时遇到问题,通过调用 regex.execute(string),而不是获取返回的捕获组数组,我总是得到单个返回,即模式中指定的整个字符串。通过在http://www.regexr.com/ 中使用相同的模式,我可以很好地看到返回分组。我错过了什么:

Private Sub ParseFileName(strInput As String)
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strReplace

    'Sample string \\Work_DIR\FTP\Results\RevA\FTP_01_01_06_Results\4F\ACC2X2R33371_SASSSD_run1
    strPattern = "FTP_(\w+)_Results\\(\w+)\\([\d,\D]+)_(SAS|SATA)(HDD|SSD)_run(\d)"

    With regEx
        .Global = True
        .MultiLine = False
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strInput) Then
        Set strReplace = regEx.Execute(strInput)
        ActiveCell.Offset(0, 1) = strReplace.Count
    Else
        ActiveCell.Offset(0, 1) = "(Not matched)"
    End If
End sub
Run Code Online (Sandbox Code Playgroud)

最后strReplace.Count总是显示1,也就是整个字符串FTP_01_01_06_Results\4F\ACC2X8R133371_SASSSD_run1

ome*_*pes 6

使用.SubMatches得到捕获组值:

Private Sub ParseFileName(strInput As String)
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strReplace As MatchCollection
    Dim i As Long

    'Sample string \\Work_DIR\FTP\Results\RevA\FTP_01_01_06_Results\4F\ACC2X2R33371_SASSSD_run1
    strPattern = "FTP_(\w+)_Results\\(\w+)\\([\d,\D]+)_(SAS|SATA)(HDD|SSD)_run(\d)"

    With regEx
        .Global = True
        .MultiLine = False
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strInput) Then
        Set strReplace = regEx.Execute(strInput)
        ActiveCell.Offset(0, 1) = strReplace.Count
        For i = 0 To 5
            ActiveCell.Offset(i + 1, 1) = strReplace(0).SubMatches(i)
        Next
    Else
        ActiveCell.Offset(0, 1) = "(Not matched)"
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)