Python re.findall打印所有模式

时间:2013-07-04 10:05:51

标签: python regex findall

>>> match = re.findall('a.*?a', 'a 1 a 2 a 3 a 4 a')
>>> match
['a 1 a', 'a 3 a']

如何打印

['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']

谢谢!

3 个答案:

答案 0 :(得分:6)

我认为使用积极的先行断言应该可以解决问题:

>>> re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')
['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']

re.findall返回正则表达式中的所有组 - 包括那些在预测中的组。这是有效的,因为前瞻断言不会消耗任何字符串。

答案 1 :(得分:5)

您可以使用替代regex模块,该模块允许重叠匹配:

>>> regex.findall('a.*?a', 'a 1 a 2 a 3 a 4 a', overlapped = True)
['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']

答案 2 :(得分:4)

r = re.compile('a.*?a') # as we use it multiple times
matches = [r.match(s[i:]) for i in range(len(s))] # all matches, if found or not
matches = [m.group(0) for m in matches if m] # matching string if match is not None
print matches

给出

['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']

我不知道它是否是最佳解决方案,但在这里我测试每个到达字符串末尾的子字符串以匹配给定的模式。