关于VBA中的lookbehinds有很多问题。问题是,虽然有正面和负面的前瞻,但VBA doesn't support lookbehinds根本就没有。
人们提出的大多数问题试图解决从文本中提取字符串的一个非常具体的问题,Stack Overflow社区已经very helpful为这些特定情况提供workarounds 。我的问题是,您是否可以在VB中编写一个函数,通过接受正则表达式作为参数并在结果字符串中执行某种查找替换来模拟正向后观,仅返回所需的匹配组,同时省略(必需但未捕获)前缀?
答案 0 :(得分:0)
以下函数接受三个参数以满足此问题:要匹配的字符串,不可捕获前缀的正则表达式模式以及后续捕获组的正则表达式模式。
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项目的参考。
答案 1 :(得分:0)
用更少的工作量就能得出与您的答案相同的结果吗? (当然,它需要添加错误检查。)
json