所以我在VBA中处理相当复杂的正则表达式。霍雷对我来说。在VBA中不支持Lookbehind。细
一个潜在的黑客是说“字符串从位置X开始”,并截断字符串以仅搜索第一部分。我不想走这条路,但如果必须,我会的。
看起来很有希望的东西是捕捉群体。
有没有办法只从正则表达式返回捕获组?
代码:
Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
Dim replaceNumber As Integer
strInput = Replace(strInput, Chr(160), " ")
With inputRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = matchPattern
End With
With outputRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = "\$(\d+)"
End With
With outReplaceRegexObj
.Global = True
.MultiLine = True
.IgnoreCase = True
End With
Set inputMatches = inputRegexObj.Execute(strInput)
If inputMatches.Count = 0 Then
regex = ""
Else
Set replaceMatches = outputRegexObj.Execute(outputPattern)
For Each replaceMatch In replaceMatches
replaceNumber = replaceMatch.SubMatches(0)
outReplaceRegexObj.Pattern = "\$" & replaceNumber
If replaceNumber = 0 Then
outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)
Else
If replaceNumber > inputMatches(0).SubMatches.Count Then
'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
regex = CVErr(xlErrValue)
Exit Function
Else
outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
End If
End If
Next
regex = outputPattern
End If
End Function
简单示例:
Regex("ABC123","ABC(123)")
复杂样本/所需结果:
字符串:ABC 33-99 AA 100-00
否定的前瞻可能会在这里工作。
字符串:123 // 45; 123 //; 123
我希望能够在一个地方获得123,在另一个地方获得45。但是当我需要向后看以建立先前的数字时,怎样才能对45进行负面的前瞻性工作呢?