Answers:
使用re.findall或re.finditer代替。
re.findall(pattern, string) 返回匹配字符串的列表。
re.finditer(pattern, string)返回MatchObject对象上的迭代器。
例:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
finditer是我一直在寻找的东西。我很惊讶一个返回Match对象,另一个返回字符串。我期待使用match_all或match_iter函数。
re.search循环使用。它将返回一个Match对象。您需要将其Match.start() + 1作为循环的下一次迭代的pos参数传递re.search。
findall则将返回匹配的元组列表,而不是匹配的字符串列表。