Hee*_*Hee 6 python regex findall
>>> match = re.findall('a.*?a', 'a 1 a 2 a 3 a 4 a')
>>> match
['a 1 a', 'a 3 a']
Run Code Online (Sandbox Code Playgroud)
如何打印它
['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']
Run Code Online (Sandbox Code Playgroud)
谢谢!
我认为使用积极的先行断言应该可以做到这一点:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
re.findall返回正则表达式中的所有组 - 包括前瞻中的组.这是有效的,因为前瞻断言不会消耗任何字符串.
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
Run Code Online (Sandbox Code Playgroud)
给
['a 1 a', 'a 2 a', 'a 3 a', 'a 4 a']
Run Code Online (Sandbox Code Playgroud)
我不知道这是否是最好的解决方案,但在这里我测试到达字符串末尾的每个子字符串以匹配给定的模式。
您可以使用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']
Run Code Online (Sandbox Code Playgroud)