有人可以解释这个Python re.sub()意外输出吗?

时间:2009-07-28 09:19:46

标签: python regex

我正在使用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'

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

3 个答案:

答案 0 :(得分:7)

是的,第四个参数是count,而不是flags。你告诉它应用模式两次(re.IGNORECASE = 2)。

答案 1 :(得分:4)

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

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

答案 2 :(得分:0)

如果你提出这个问题就升级了。如果您使用的是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