特別な構文 $[VARIABLE] (角括弧に注意) と string.template.safe_substitute() を使用して変数を置き換えようとする Python コードがあります。これは正常に機能していますが、未定義の変数が参照された場合、safe_substitute() が文書化されているため、参照をそのままにしておくのではなく、角括弧を中括弧に置き換えるという 1 つの例外があります。テンプレートでの RE の高度な使用法は詳細に文書化されていないため ( http://docs.python.org/2/library/string.html#template-strings )、おそらく間違って使用しているだけです。アイデア?
テスト ケースの実行例を次に示します。var が定義されている場合、すべてが正常に機能することに注意してください。
% python tmpl.py
===$[UNDEFINED]===
===${UNDEFINED}===
% UNDEFINED=Hello python tmpl.py
===$[UNDEFINED]===
===Hello===
テストケース自体は次のとおりです。
import os
from string import Template
# The strategy here is to replace $[FOO] but leave traditional
# shell-type expansions $FOO and ${FOO} alone.
# The '(?!)' below is a guaranteed-not-to-match RE.
class _Replace(Template):
pattern = r"""
\$(?:
(?P<escaped>(?!)) | # no escape char
(?P<named>(?!)) | # do not match $FOO, ${FOO}
\[(?P<braced>[A-Z_][A-Z_\d]+)\] | # do match $[FOO]
(?P<invalid>)
)
"""
if '__main__' == __name__:
text = '===$[UNDEFINED]==='
tmpl = _Replace(text)
result = tmpl.safe_substitute(os.environ)
print text
print result