简体   繁体   English

Python re.findall打印所有模式

[英]Python re.findall print all patterns

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

How do I get it to print 如何打印它

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

Thank you! 谢谢!

I think using a positive lookahead assertion should do the trick: 我认为使用积极的先行断言应该可以做到这一点:

>>> 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 returns all the groups in the regex - including those in look-aheads. re.findall返回正则表达式中的所有组 - 包括那些在re.findall的组。 This works because the look-ahead assertion doesn't consume any of the string. 这是有效的,因为前瞻断言不会消耗任何字符串。

You may use alternative regex module which allows overlapping matches: 您可以使用允许重叠匹配的替代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']
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

gives

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

I don't know if it is the best solution, but here I test every substring reaching to the end of the string for matching with the given pattern. 我不知道它是否是最好的解决方案,但在这里我测试每个到达字符串末尾的子字符串以匹配给定的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM