- 此问题在此处已有答案**:
re.findall behaves weird(3个答案)
6天前关闭。
1.使用findall:
import re
target_string = "please sir, that's obviously a clip-on."
result = re.findall(r"[a-z]+('[a-z])?[a-z]*", target_string)
print(result)
# result: ['', '', "'s", '', '', '', '']
1.使用查找器:
import re
target_string ="please sir, that's obviously a clip-on."
result = re.finditer(r"[a-z]+('[a-z])?[a-z]*", target_string)
matched = []
for match_obj in result:
matched.append(match_obj.group())
print(matched)
# result: ['please', 'sir', "that's", 'obviously', 'a', 'clip', 'on']
这两种方法是如何匹配模式的,为什么结果输出有差异。请解释。
尝试阅读文档,但仍然对findall与finditer的工作原理感到困惑
1条答案
按热度按时间b1zrtrql1#
在
findall
的情况下,输出将是捕获组('[a-z])
。如果您希望完全匹配,请将您的组转换为非捕获组(?:'[a-z])
:输出:
请注意,如果有多个捕获组,
findall
将返回它们的元组: