Search code examples
regexpython-3.xpattern-matchingfindall

finding all matches in a string using regex


I have used re.findall() to get all the matches in my string. I have my string "aaadaa" and want to search 'aa' in it. I want it to return me three instances of 'aa'. i.e. output should be ['aa','aa','aa']. However I am getting only ['aa','aa']. How to get my desired output?

import re
s= "aaadaa"
regex = 'aa'
matches = re.findall(regex, s)
print(matches)

Solution

  • You can try (?=(aa))

    The trick is that you use positive lookahead, which doesn't consume string, this way engine starts matching at the next position in string, not after last matched text.

    You will get 3 matches and each will have aa in first captuirng group.

    Demo