我使用以下方法替换testscript中的变量(简化):
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!`.
在varreplace中,我必须剥去大括号{}
,使其变得丑陋(例如,当我将模式更改为双括号时,我必须更改varreplace函数)
是否有方法将大括号放在模式中,但不将它们包含在替换字符串中?我想使用通用varreplace
函数,而不必担心变量标识符的格式和长度。
答案 0 :(得分:1)
要摆脱{},请将模式更改为
re_.pattern = "\{([a-zA-Z][\w ]*)\}"
和替换函数:
Private Function varreplace(sMatch, sGroup1, nPos, sSrc)
varreplace = mydict(sGroup1)
End Function
使用(普通)组捕获()捕获大括号之间的序列并向函数添加参数使得字典键可以立即访问。