模拟VBA正则表达式的总体正向后看 [英] Simulate a general positive lookbehind for VBA regex
问题描述
在VBA中,有很多关于回溯的问题.问题是,尽管有正面和负面的前瞻,但VBA 不支持 完全看不见.
There are a plethora of questions about lookbehinds in VBA. The problem is that, while there are positive and negative lookaheads, VBA doesn't support lookbehinds at all.
人们提出的大多数问题试图解决一个非常具体的问题,即从文本中提取字符串,而Stack Overflow社区已经成为为这些特殊情况提供解决方法很有帮助.我的问题是,您是否可以在VB中编写一个函数,通过接受正则表达式模式作为参数并在结果字符串中执行某种查找替换来模拟正向后看,以在不省略(必需但未捕获)前缀的情况下仅返回所需的匹配组?
Most of the questions people have asked seek to solve a very specific problem of extracting strings from text and the Stack Overflow community has been very helpful in providing workarounds for these particular cases. My question is, could you write a function in VB that simulates positive lookbehind by accepting Regex patterns as arguments and doing some kind of find-replace in the resulting string to only return the desired match group while omitting a (required but not captured) prefix?
推荐答案
以下函数接受三个参数来满足此问题:要匹配的字符串,不可捕获前缀的regex模式和regex模式后续捕获组中的一个.
The following function accepts three arguments in order to satisfy this problem: a string to be matched, the regex pattern of a non-capturable prefix, and the regex pattern of the subsequent capture group.
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项目的引用.
Limitations: This will only simulate positive lookbehind. The relevant Regular Expressions module must be added as a reference to the VB project.
这篇关于模拟VBA正则表达式的总体正向后看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!