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!
CodePudding user response:
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']