2012-03-06 3 views
1
私はにTestScriptで変数を交換するには、次の方法を使用し

を交換する値でそれらを除外する方法を、交換してください(簡体字):varreplaceで使う正規表現がマッチパターンの文字が含まれるが、

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関数を使用して、変数識別子の形式と長さについて悩まされることはありません。

+0

文字列の前後の例は何ですか?この関数の入力と出力の例は何でしょうか?私は(ソース?)辞書に括弧を見ません。あなたが達成したいことを理解していれば、中括弧を無視する(または少なくとも無視する)ことは問題ではありません。 –

+0

コードを多少下にスクロールすると、前後のテキストの例が表示されます(折り返しのすぐ下にあります)。 – AutomatedChaos

答えて

1

、{}を取り除く

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

にパターンを変更してに機能を交換する:(プレーン)基キャプチャを使用して

括弧の間の配列をキャプチャー
Private Function varreplace(sMatch, sGroup1, nPos, sSrc) 
    varreplace = mydict(sGroup1) 
End Function 

( )、関数にパラメータを追加すると、辞書のキーにすぐにアクセスできます。

+0

魅力的な作品です!どうもありがとうございました! – AutomatedChaos

関連する問題