Excel VB Regexp 5.5 捕获组

3

我在使用Excel宏中的正则表达式时遇到了问题。当调用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个回答

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

太棒了,这个可行!非常感谢!抱歉,无法点赞。 - SamDaMan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接