[英]Find String between characters with multiple occurences in Python
So I want to find a string between 2 characters.所以我想找到一个介于 2 个字符之间的字符串。 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.但我更想要的是我分别得到第一次出现的“cmd”和第二次出现的“cmd2”。 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()
:您需要使捕获组非贪婪,并且要获取所有事件,您应该使用
re.findall()
而不是re.search()
:
result = re.findall('<(.*?)>', str)
This outputs:这输出:
['cmd', 'cmd2']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.