简体   繁体   中英

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'. ie 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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