我试图用 $varname 语法来实施简单的 shell 风格字符串变量内插, 使用 pyparsing 。 例如, 如果我有一个变量 < code> foo code >, 值为 < code> bar code >, 然后将 < code > > x $foo x " code> 转换为 < code> x bar x " code> 。
但是,当 $
前面有一个反斜线时,我想防止变量内插。 因此, "x $foo x"
应该留在 x $foo x"
。 我使用 pyparsing s transform_string
。 我试图添加负面头,以避免对以 开头的字符串进行解析。 但是它不起作用 。
import pyparsing as pp
vars = {"foo": "bar"}
interp = pp.Combine(
~pp.Literal("\")
+ pp.Literal("$").suppress()
+ pp.common.identifier.set_parse_action(lambda t: vars[t[0]])
)
print(interp.transform_string("x $foo x"))
print(interp.transform_string("x \$foo x"))
这一产出:
x bar x
x ar x
但我喜欢它输出:
x bar x
x $foo x
我怀疑在剖析器开始时的负外观与 transform_string
无效, 因为它仍然可以找到一个子字符串, 而没有该子字符串 。 但我不确定如何解决这个问题 。