Sachin Suresh
Sachin Suresh

Reputation: 15

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)

Upvotes: 1

Views: 280

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37377

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

Upvotes: 1

Related Questions