用正则表达式替换捕获的组

时间:2016-10-13 02:55:03

标签: regex vba

是否可以执行以下操作:

Sub GetANewDirectory()
    Dim MyString As String
    MyString = "C:\File1\File2\File3\AnImportantFile.txt"

    Dim MyRegEx As New VBScript_RegExp_55.RegExp
    With MyRegEx
        .Global = True
        .IgnoreCase = True
        .MultiLine = False
        .Pattern = ".*(File1)\\(File2)\\(File3).*"
    End With

    Dim MyMatch As Variant        
    Set MyMatch = MyRegEx.Execute(MyString)

    ' The following syntax doesn't work
    MyMatch(0).SubMatches(0) = Func1(MyMatch(0).SubMatches(0))
    MyMatch(0).SubMatches(1) = Func2(MyMatch(0).SubMatches(1))
    MyMatch(0).SubMatches(2) = Func3(MyMatch(0).SubMatches(2))

    Debug.Print MyMatch(0)
    ' My desired result is:
    ' C:\File1Apple\File2Banna\File3Mango\AnImportantFile.txt
End Sub

Function Func1(Arg1 As String) As String
    Func1 = Arg1  & "Apple"
End Function

Function Func2(Arg1 As String) As String
    Func2 = Arg1 & "Banna"
End Function

Function Func3(Arg1 As String) As String
    Func3 = Arg1 & "Mango"
End Function

如果这看起来有点抽象,我很抱歉,但我真的需要这样的东西。我确信我可以在没有正则表达式的情况下完成任务,但我可以看到这种功能在哪些方面很有用。

1 个答案:

答案 0 :(得分:0)

如果您确实需要使用外部函数来处理操作,那么最佳选择(使用正则表达式)是将函数指针传递到.Replace对象的RegExp方法。该函数将作为参数接收:

  1. RegExp
  2. 中的模式匹配的字符串部分
  3. 模式中每个捕获组的一个参数
  4. 模式匹配的原始字符串内的偏移量
  5. 原始字符串
  6. 该函数必须返回将替换与模式匹配的原始字符串部分的字符串。

    Option Explicit
    
    Dim MyString
        MyString = "C:\File1\File2\File3\AnImportantFile.txt"
    
        With New RegExp
            .Global = True
            .IgnoreCase = True
            .MultiLine = False
            ' groups:     (1     )  (2     )  (3     )
            .Pattern = "\\([^\\]+)\\([^\\]+)\\([^\\]+)\\"
            MyString = .Replace(MyString, GetRef("ReplaceHandler"))
        End With 
    
        WScript.Echo MyString
    
    
    Function ReplaceHandler( matchedString, group1, group2, group3, offset, originalString )
        ReplaceHandler = Join(Array("", Func1(group1), Func2(group2), Func3(group3), ""), "\")
    End Function    
    
    Function Func1( Arg1 ) 
        Func1 = Arg1  & "Apple"
    End Function
    Function Func2( Arg1 ) 
        Func2 = Arg1 & "Banna"
    End Function
    Function Func3( Arg1 ) 
        Func3 = Arg1 & "Mango"
    End Function