为什么 re.findall() 比 re.sub() 找到更多的匹配? [英] Why does re.findall() find more matches than re.sub()?

查看:34
本文介绍了为什么 re.findall() 比 re.sub() 找到更多的匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下事项:

<预><代码>>>>进口重新>>>a = "第一:第二">>>re.findall("[^:]*", a)['第一秒', '']>>>re.sub("[^:]*", r"(\g<0>)", a)'(第一秒)'

re.sub() 的行为最初更有意义,但我也能理解 re.findall() 的行为.毕竟,您可以在 first: 之间匹配一个空字符串,该字符串仅包含非冒号字符(恰好为零),但为什么不是 re.sub() 行为相同吗?

最后一条命令的结果不应该是(first)():(second)()吗?

解决方案

您使用允许空匹配的 *:

'first' ->匹配':' ->不在字符类中,但由于模式可能为空到 *,匹配一个空字符串 -->'''第二' ->匹配'$' ->之前可以包含一个空字符串,匹配一个空字符串 -->''

引用 re.findall() 的文档:

<块引用>

空匹配包含在结果中,除非它们触及另一匹配的开头.

您没有在子结果中看到空匹配的原因在 文档中解释了<代码>re.sub():

<块引用>

模式的空匹配仅在与前一个匹配不相邻时才被替换.

试试这个:

re.sub('(?:Choucroute garnie)*', '#', 'ornithorynque')

现在这个:

print re.sub('(?:nithorynque)*', '#', 'ornithorynque')

没有连续的#

Consider the following:

>>> import re
>>> a = "first:second"
>>> re.findall("[^:]*", a)
['first', '', 'second', '']
>>> re.sub("[^:]*", r"(\g<0>)", a)
'(first):(second)'

re.sub()'s behavior makes more sense initially, but I can also understand re.findall()'s behavior. After all, you can match an empty string between first and : that consists only of non-colon characters (exactly zero of them), but why isn't re.sub() behaving the same way?

Shouldn't the result of the last command be (first)():(second)()?

解决方案

You use the * which allows empty matches:

'first'   -> matched
':'       -> not in the character class but, as the pattern can be empty due 
             to the *, an empty string is matched -->''
'second'  -> matched
'$'       -> can contain an empty string before,
             an empty string is matched -->''

Quoting the documentation for re.findall():

Empty matches are included in the result unless they touch the beginning of another match.

The reason you don't see empty matches in sub results is explained in the documentation for re.sub():

Empty matches for the pattern are replaced only when not adjacent to a previous match.

Try this:

re.sub('(?:Choucroute garnie)*', '#', 'ornithorynque') 

And now this:

print re.sub('(?:nithorynque)*', '#', 'ornithorynque')

There is no consecutive #

这篇关于为什么 re.findall() 比 re.sub() 找到更多的匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆