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 this is the best solution, but here I check every substring that goes to the end of the line to match the given pattern.
source share