regex 我需要一个在VBA中的正则表达式lookbehind(负和正)的替代[duplicate]

2nbm6dog  于 2022-12-14  发布在  其他
关注(0)|答案(3)|浏览(153)

此问题在此处已有答案

Using regex with positive lookbehind in VBA(1个答案)
昨天关门了。
我需要匹配一个txt文件中的所有:,但避免它们前面有httpshttp\,但VBA不支持正则表达式的lookbehind。
使用负向后查找,它应该是(?<!http)(?<!https)(?<!\\)\:
对于某些不支持lookbehind的引擎,它可以是([^https*][^\\])\K\:
这两个正则表达式在VBA中都不起作用,第一个正则表达式给我一个错误(5017),第二个正则表达式忽略所有:,但代码没有抛出任何错误。
基于regEx positive lookbehind in VBA language,我在一个小例子中测试了这一点:

myString = "BA"
pattern = "[^B](A)"
myString = rg.Replace(myString,"$1")

预期的结果是"A",但得到的结果是"BA"。我错过了什么?
解决方案在这篇文章:Using regex with positive lookbehind in VBA它没有出现在我的搜索中,因为标题说的是积极的回顾,而我的问题是关于消极的回顾。

0h4hbjxa

0h4hbjxa1#

“诀窍”是匹配你不想要的,但然后捕获你想要的,并只返回捕获的组。例如:

Sub regex()
    Dim RE As Object, MC As Object, M As Object
    Const sPat As String = "B(A)"
    Const myString As String = "BA"
    
Set RE = CreateObject("vbscript.regexp")
With RE
    .Pattern = sPat
    Set MC = .Execute(myString)
    Debug.Print MC(0).submatches(0)
End With
    
    
End Sub

will =〉A立即窗口中

e0bqpujr

e0bqpujr2#

您可以使用

Dim pattern As regExp, m As Object
Dim text As String, result As String, repl As String, offset As Long

text = "http://www1 https://www2 \: : text:..."
repl = "_"
offset = 0

Set pattern = New regExp
With pattern
    .pattern = "(https?:|\\:)|:"
    .Global = True
End With

result = text
For Each m In pattern.Execute(text)
    If Len(m.SubMatches(0)) = 0 Then ' If Group 1 matched, replace with "a"
        result = Left(result, m.FirstIndex + offset) & repl & Mid(result, m.FirstIndex + m.Length + 1 + offset)
        offset = offset + Len(repl) - m.Length
    End If
Next

http://www1 https://www2 \: : text:...的输出为http://www1 https://www2 \: _ text_...
重点是匹配并捕获https:http:\:(https?:|\\:)捕获组,然后在匹配时进行内联替换。偏移量的使用有助于跟踪不断变化的字符串长度,特别是当您需要用不同长度的字符串进行替换时。

vhmi4jdf

vhmi4jdf3#

罗恩Rosenfeld给出了查找:的代码,当:前面有http(和其他字符)时,您需要查找:,当它 * 不是 * 前面有http(和其他字符)时。

Sub regex()
    Dim RE As Object, MC As Object, M As Object
    Const sPat As String = "((https?|\\)?)(:)"
    Const myString As String = "..."
    
    Set RE = CreateObject("vbscript.regexp")
    With RE
        .Pattern = sPat
        Set MC = .Execute(myString)
        If MC(0).submatches(1) = "" Then
            Debug.Print MC(0).submatches(3)
        End If
    End With
End Sub

相关问题