excel VBA正则表达式5.5捕获组

时间:2015-03-16 22:28:44

标签: regex excel-vba vba excel

我在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

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

1 个答案:

答案 0 :(得分:4)

使用.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