【问题标题】:Can someone explain this Python re.sub() unexpected output?有人可以解释这个 Python re.sub() 意外输出吗?
【发布时间】:2009-07-28 09:19:45
【问题描述】:

我正在使用 Python 2.6,并且从 re.sub() 得到 [我认为是] 意外的输出

>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'

如果这个输出是预期的,它背后的逻辑是什么?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    是的,第四个参数是计数,不是标志。您是在告诉它应用该模式两次(re.IGNORECASE = 2)。

    【讨论】:

    • 啊,是的。混合参数。谢谢。
    【解决方案2】:

    要传递标志,您可以使用 re.compile

    expression = re.compile('[aeiou]', re.IGNORECASE)
    expression.sub('-', 'the cat sat on the mat')
    

    【讨论】:

      【解决方案3】:

      如果您在提出此问题后已升级。如果您使用的是 Python 2.7+,则不需要使用 re.compile。您可以调用 sub 并使用命名参数指定 flags

      >>> import re
      >>> re.sub('[aeiou]', '-', 'the cat sat on the mat', flags=re.IGNORECASE)
      'th- c-t s-t -n th- m-t'
      

      参考:https://docs.python.org/2/library/re.html#re.sub

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多