1

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.

2
  • What would be an example before and after string? What would be an example input and output for this function? I don't see any braces in the (source?) dictionary. Ignoring (or at least simulating ignoring) braces shouldn't be a problem, if I understand what you want to accomplish. Commented Mar 6, 2012 at 13:49
  • An example with before and after text is stated if you scroll the code somewhat down (it is located just under the fold). Commented Mar 6, 2012 at 13:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.