繁体   English   中英

Python正则表达式不一致

[英]Python regular expression inconsistency

根据我是否预编译正则表达式,我得到了不同的结果:

>>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean')
' Bean'
>>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE)
'Mr Bean'

Python文档一些函数是编译正则表达式的全功能方法的简化版本。 但是它也声称RegexObject.sub() 与sub()函数相同

那么这里发生了什么?

re.sub()无法接受re.IGNORECASE ,它出现了。

文件说明:

sub(pattern, repl, string, count=0)

  返回通过替换最左边获得的字符串\n 由字符串中的模式非重叠出现\n 替换代表  repl可以是字符串也可以是可调用的;\n 如果处理了一个字符串,则反斜杠转义。  如果是\n 一个可调用的,它传递了匹配对象,必须返回\n 要使用的替换字符串。 

然而,使用它可以取代它:

re.sub("(?i)mr", "", "Mr Bean")

模块级sub()调用最后不接受修饰符。 这就是“count”参数 - 要替换​​的模式最大出现次数。

>>> help(re.sub)
  1 Help on function sub in module re:
  2 
  3 sub(pattern, repl, string, count=0)
  4     Return the string obtained by replacing the leftmost
  5     non-overlapping occurrences of the pattern in string by the
  6     replacement repl.  repl can be either a string or a callable;
  7     if a callable, it's passed the match object and must return
  8     a replacement string to be used.

re.sub中的regex标志( IGNORECASE, MULTILINE, DOTALL )中没有函数参数,如re.compile

备择方案:

>>> re.sub("[M|m]r", "", "Mr Bean")
' Bean'

>>> re.sub("(?i)mr", "", "Mr Bean")
' Bean'

编辑 Python 3.1增加了对正则表达式标志的支持, http://docs.python.org/3.1/whatsnew/3.1.html 从3.1开始,例如re.sub的签名如下:

re.sub(pattern, repl, string[, count, flags])

从Python 2.6.4文档:

re.sub(pattern, repl, string[, count])

re.sub()不带标志来设置正则表达式模式。 如果你想要re.IGNORECASE,你必须使用re.compile()。sub()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM