【发布时间】:2015-09-10 07:37:00
【问题描述】:
我正在 Python 2.7 中试验正则表达式 RE 模块。文档指出,在 re.sub() 函数中,count 参数是可选的。如果它丢失或设置为 0,则所有匹配项都将被替换。但事实并非如此。请特别注意“re.I”或“re.M”存在但组参数缺失时的处理差异:
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> a = "The brown fox over the little doggy which moved."
>>> b = re.sub(r'o\w','au',a)
>>> print b
The braun fau auer the little daugy which maued.
>>> b = re.sub(r'o\w','au',a,2)
>>> print b
The braun fau over the little doggy which moved.
>>> b = re.sub(r'o\w','au',a,re.I)
>>> print b
The braun fau over the little doggy which moved.
>>> b = re.sub(r'o\w','au',a,flags=re.I)
>>> print b
The braun fau auer the little daugy which maued.
>>> b = re.sub(r'o\w','au',a,re.M)
>>> print b
The braun fau auer the little daugy which maued.
这是 Python 中的预期行为吗?如果是这样,那是不是说明代码不可靠?
【问题讨论】:
-
到底是什么问题?为什么不可靠?
-
这里的不一致在哪里?例如,您将
re.I作为count参数传递,而re.I是一个等于2 的整数,因此您得到了两个替换。re.M是 8,所以你有 8 个替换。 -
所以 re.I 或 re.M 被读作计数参数?这是预期的行为?嗯...好吧,我学到了一些新东西。谢谢!
标签: python regex optional-parameters