简体   繁体   中英

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!

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']

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