
[英]Why does re.findall() give me different results than re.finditer() in Python?
[英]python re: search and findall give different results [duplicate]
为什么 search 和 findall 给出不同的结果?
result = re.search(r'Bat(wo)?man', 'The Adventures of Batman')
print(result) # found
re.findall(r'Bat(wo)?man', 'The Adventures of Batman') # empty list
当我运行它时,我没有得到一个空列表,而是一个包含单个空字符串的列表: ['']
。
从文档(强调我的):
结果取决于模式中捕获组的数量。 如果没有组,则返回与整个模式匹配的字符串列表。 如果只有一个组,则返回与该组匹配的字符串列表。 如果存在多个组,则返回与组匹配的字符串元组列表。 非捕获组不影响结果的形式。
您使用捕获组 ( (wo)?
),因此结果仅包含与该组匹配的字符串部分。
您可以通过将组更改为非捕获组来解决此问题:
>>> print(re.findall(r'Bat(?:wo)?man', 'The Adventures of Batman'))
['Batman']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.