'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!
Solution 1:[1]
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']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
