How to mimic regular Expression negative lookbehind?

不打扰是莪最后的温柔 提交于 2021-02-05 08:11:24

问题


What I'm trying to accomplish

I'm trying to create a function to use string interpolation within VBA. The issue I'm having is that I'm not sure how to replace "\n" with a vbNewLine, as long as it does not have the escape character "\" before it?


What I have found and tried

VBScript does not have a negative look behind as far as I can research.

Below has two examples of Patterns that I have already tried:

Private Sub testingInjectFunction()
    Dim dict As New Scripting.Dictionary
    dict("test") = "Line"
    Debug.Print Inject("${test}1\n${test}2 & link: C:\\notes.txt", dict)
End Sub    
Public Function Inject(ByVal source As String, dict As Scripting.Dictionary) As String
    Inject = source

    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
    regEx.Global = True

    ' PATTERN # 1 REPLACES ALL '\n'
    'regEx.Pattern = "\\n"

    ' PATTERN # 2 REPLACES EXTRA CHARACTER AS LONG AS IT IS NOT '\'
    regEx.Pattern = "[^\\]\\n"

    ' REGEX REPLACE
    Inject = regEx.Replace(Inject, vbNewLine)

    ' REPLACE ALL '${dICT.KEYS(index)}' WITH 'dICT.ITEMS(index)' VALUES
    Dim index As Integer
    For index = 0 To dict.Count - 1
        Inject = Replace(Inject, "${" & dict.Keys(index) & "}", dict.Items(index))
    Next index

End Function

Desired result

Line1
Line2 & link: C:\notes.txt

Result for Pattern # 1: (Replaces when not wanted)

Line1
Line2 & link: C:\
otes.txt

Result for Pattern # 2: (Replaces the 1 in 'Line1')

Line
Line2 & link: C:\\notes.txt

Summary question

I can easily write code that doesn't use Regular Expressions that can achieve my desired goal but want to see if there is a way with Regular Expressions in VBA.

How can I use Regular Expressions in VBA to Replace "\n" with a vbNewLine, as long as it does not have the escape character "\" before it?


回答1:


Yes, you may use a regex here. Since the backslash is not used to escape itself in these strings, you may modify your solution like this:

regEx.Pattern = "(^|[^\\])\\n"
S = regEx.Replace(S, "$1" & vbNewLine)

It will match and capture any char but \ before \n and then will put it back with the $1 placeholder. As there is a chance that \n appears at the start of the string, ^ - the start of string anchor - is added as an alternative into the capturing group.

Pattern details

  • (^|[^\\]) - Capturing group 1: start of string (^) or (|) any char but a backslash ([^\\])
  • \\ - a backslash
  • n - a n char.


来源:https://stackoverflow.com/questions/49581881/how-to-mimic-regular-expression-negative-lookbehind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!