尝试了解 findall 与 finditer 的匹配内容和结果输出的差异[重复]

问题描述 投票:0回答:1
  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 的工作原理感到困惑

python regex string iteration
1个回答
0
投票

findall
情况下,输出将是捕获组
('[a-z])
。 如果您想要完整的比赛,请将您的团队转变为非捕获团队
(?:'[a-z])

target_string = "please sir, that's obviously a clip-on."
result = re.findall(r"[a-z]+(?:'[a-z])?[a-z]*", target_string)
print(result)

输出:

['please', 'sir', "that's", 'obviously', 'a', 'clip', 'on']

请注意,如果您有多个捕获组,

findall
将返回它们的元组:

re.findall(r"([a-z]+('[a-z])?[a-z]*)", target_string)

[('please', ''), ('sir', ''), ("that's", "'s"), ('obviously', ''), ('a', ''), ('clip', ''), ('on', '')]
© www.soinside.com 2019 - 2024. All rights reserved.