【发布时间】:2014-09-21 13:10:43
【问题描述】:
我有以下代码作为我正在处理的 css 预处理器的一部分。本节采用用户定义的变量并将它们插入到代码中。正则表达式仅在被空格、大括号、方括号、逗号、引号或运算符包围时才替换。当我运行它时,我只会每隔一次替换一次变量。
def insert_vars(ccss, variables):
for var in variables.keys():
replacer = re.compile(r"""(?P<before>[,+\[(\b{:"'])\$""" + var + """(?P<after>[\b}:"'\])+,])""")
ccss = replacer.sub(r"\g<before>" + variables[var] + r"\g<after>", ccss)
del replacer
re.purge()
return ccss.replace(r"\$", "$")
当我运行它时
insert_vars("hello $animal, $nounification != {$noun}ification.", {"animal": "python", "noun": "car"})
50% 的时间返回
hello $animal, $nounification != {car}ification.
另外 50%
hello $animal, $nounification != {$noun}ification.
有人知道为什么吗?
【问题讨论】:
-
我只是在想,为什么不呢?
-
嗯...我得到
'hello $animal, $nounification != {car}ification.'100% 的时间。不管怎样,看起来return语句是for循环的一部分:也许它应该移到它外面?