regex每次运行给出不同的结果

2024-09-28 21:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码作为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.

有人知道为什么吗?你知道吗


Tags: 代码rehellovarvarsvariablesinsertnoun
2条回答

实际情况是,您的return关键字是循环的一部分,如acjr stated in the comments。你知道吗

这意味着循环只能运行一次迭代。你知道吗

.keys()的顺序未定义,'animal''noun'可以排在第一位。你知道吗

有一半的时间,你的代码会先得到'noun',这是正确的,或者先得到'animal',这是没有效果的。你知道吗

因此,应该将return的缩进减少到循环之外。你知道吗

def insert_vars(ccss, variables):
    pattern = re.compile(r"\$(?P<key>\w+)")
    def replacer(match):
        return variables.get(match.group('key'), match.group(0))
    return pattern.sub(replacer, ccss)

相关问题 更多 >