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

Find String between characters with multiple occurences in Python

So I want to find a string between 2 characters.
I already did that like this:

import re
str = "Please use <cmd> and after that <cmd2>!"
result = re.search('<(.*)>', str)
print(result.group(1)

The problem about this is that if I perform it it prints the text between the first < and the last > which is not exactly what I want.

cmd> and after that <cmd2

But what I rather want is that I get the first occurence "cmd" and then the second occurence "cmd2" seperatly.
I appreciate your help!

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

>Solution :

You need to make the capture group non-greedy, and to get all the occurrences, you should use re.findall() rather than re.search():

result = re.findall('<(.*?)>', str)

This outputs:

['cmd', 'cmd2']
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