AutomatedChaos
AutomatedChaos

Reputation: 7490

Using regex replace, how to include characters in the match pattern but exclude them in the value to replace

I use the following method to replace variables in a testscript (simplified):

Dim myDict
Set myDict = createobject("scripting.dictionary")
mydict.add "subject", "testobject"
mydict.add "name", "callsign"
mydict.add "testobject callsign here", "Chell"
mydict.add "subject hometown here", "City 17"

Class cls_simpleReplacer

    Private re_

    Public Sub Class_Initialize
        Set re_ = new regexp
        re_.global = true
        re_.pattern = "\{[a-zA-Z][\w ]*\}"
    End Sub

    Public Function Parse(myString)
        dim tStr

        tStr = re_.replace(myString, getref("varreplace"))

        ' see if there was a change
        If tStr <> myString Then
            ' see if we can replace more
            tStr = Parse(tStr)
        End If

        Parse = tStr
    End Function

End Class

Private Function varreplace(a, b, c)
    varreplace = mydict.Item(mid(a, 2, len(a) - 2))
End Function

MsgBox ((new cls_simpleReplacer).Parse("Unbelievable. You, {{subject} {name} here}, must be the pride of {subject hometown here}!"))
' This will output `Unbelievable. You, Chell, must be the pride of City 17!`. 

In the varreplace, I have to strip the braces {}, making it ugly (when I change the pattern to double braces for example, I have to change the varreplace function)

Is there a method to put the braces in the pattern, but without including them in the replacement string? I want to use a generic varreplace function without bothering about the format and length of the variable identifiers.

Upvotes: 1

Views: 976

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

To get rid of the {}, change the pattern to

re_.pattern = "\{([a-zA-Z][\w ]*)\}"

and the replace function to:

Private Function varreplace(sMatch, sGroup1, nPos, sSrc)
   varreplace = mydict(sGroup1)
End Function

Capturing the sequence between the braces by using (plain) group capture () and adding a parameter to the function makes the dictionary key immediately accessible.

Upvotes: 1

Related Questions