Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex: get all matches in between two set substrings

If I have a sentence similar to the following:

aabcadeaaabbacababe

and I want to get all of the text where it starts with c and ends with e, so that it matches like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['ad', 'abab']

is it possible to achieve this? I have tried using lookarounds and c(.*)e, but instead of returning as separate entities in a list, they are combined into one substring that only looks for the first c and the last e.

>Solution :

Try to change your c(.*)e to c(.*?)e, which will make the match non-greedy.

import re

r = re.findall(r'c(.*?)e', 'aabcadeaaabbacababe')
print(r)  # ['ad', 'abab']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading