Regex 模拟VBA正则表达式的一般正向查找

Regex 模拟VBA正则表达式的一般正向查找,regex,vba,excel,regex-lookarounds,Regex,Vba,Excel,Regex Lookarounds,关于VBA中的lookbehind有很多问题。问题是,虽然有正面和负面的外观,但VBA根本不存在 人们提出的大多数问题都是为了解决从文本中提取字符串这一非常特殊的问题,而堆栈溢出社区一直在为这些特殊情况提供解决方案。我的问题是,您是否可以在VB中编写一个函数,通过接受正则表达式模式作为参数并在结果字符串中执行某种查找替换来模拟正向查找,从而仅返回所需的匹配组,同时省略(必需但未捕获)前缀 以下函数接受三个参数以解决此问题:要匹配的字符串、不可捕获前缀的正则表达式模式以及后续捕获组的正则表达式模式

关于VBA中的lookbehind有很多问题。问题是,虽然有正面和负面的外观,但VBA根本不存在


人们提出的大多数问题都是为了解决从文本中提取字符串这一非常特殊的问题,而堆栈溢出社区一直在为这些特殊情况提供解决方案。我的问题是,您是否可以在VB中编写一个函数,通过接受正则表达式模式作为参数并在结果字符串中执行某种查找替换来模拟正向查找,从而仅返回所需的匹配组,同时省略(必需但未捕获)前缀

以下函数接受三个参数以解决此问题:要匹配的字符串、不可捕获前缀的正则表达式模式以及后续捕获组的正则表达式模式

Function LookBehindRegex(ByVal inputText As String, nonCaptureRegex As String, _
   captureRegex As String)

    'Non capturing lookbehind to retrieve reference preceded by a regex group

    Dim regEx As New RegExp
    Dim intermediate As String
    Dim nonCaptureText As String

    regEx.IgnoreCase = True
    'First set the capture pattern to both regex groups, to capture the whole text
    regEx.Pattern = "(" & nonCaptureRegex & ")" & "(" & captureRegex & ")"
    'Store that
    intermediate = regEx.Execute(inputText)(0)
    'Next, set the pattern to only capture the non-capture regex
    regEx.Pattern = nonCaptureRegex
    'Store the non-capturable text from the intermediate result
    nonCaptureText = regEx.Execute(intermediate)(0)
    'Finally remove the non-capture text from the intermediate result
    LookBehindRegex = Replace(intermediate, nonCaptureText, "")

End Function

限制:这将只模拟积极的后视。必须添加相关的正则表达式模块作为对VB项目的引用。

这不是会以更少的工作量给出与您的答案相同的结果吗?(当然,它需要添加错误检查。)


您的答案只是另一个基于捕获机制的常见解决方法。它可以写得更简单。
Function LookBehindRegex( _
    ByVal inputText As String, nonCaptureRegex As String, _
    captureRegex As String) As String

    Dim regEx As New RegExp
    Dim mac As MatchCollection

    regEx.IgnoreCase = True
    regEx.Pattern = "(" & nonCaptureRegex & ")(" & captureRegex & ")"

    Set mac = regEx.Execute(inputText)
    If mac.Count > 0 Then _
        LookBehindRegex = mac(0).SubMatches(1)

End Function