【问题标题】:regex gives different results each run正则表达式每次运行都会给出不同的结果
【发布时间】: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 循环的一部分:也许它应该移到它外面?

标签: python regex parsing


【解决方案1】:

发生的事情是您的 return 关键字是循环的一部分,如 acjr stated in the comments

这意味着循环只会运行一次迭代。

.keys() 的顺序未定义,'animal''noun' 可以先出现。

有一半的时间,您的代码会先获得'noun',这会正常工作,或者先获得'animal',这将没有任何效果。

因此,您应该将return 的缩进减少到循环之外。

【讨论】:

  • 我也想过这一点,但不太确定,因为我希望使用 $ 语法可以访问变量。我可能会将其转换为格式语法。
  • @user229276 啊,我以为用户只会提供变量,而不是源。我没有读过关于 CSS 预处理器的文章。
  • @user229276 我已经编辑了答案以解释您当前代码的问题。
  • 天哪,谢谢。我开始认为 python 正则表达式引擎或其他东西有些奇怪。 :)
【解决方案2】:
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)

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2012-05-02
    相关资源
    最近更新 更多