[英]python regex: match to the first “}”
I have a string s
containing:- 我有一个字符串
s
包含:
Hello {full_name} this is my special address named {address1}_{address2}.
I am attempting to match all instances of strings that is contained within the curly brackets. 我试图匹配花括号中包含的所有字符串实例。
Attempting:- 尝试:-
matches = re.findall(r'{.*}', s)
gives me 给我
['{full_name}', '{address1}_{address2}']
but what I am actually trying to retrieve is 但是我实际上试图检索的是
['{full_name}', '{address1}', '{address2}']
How can I do that? 我怎样才能做到这一点?
>>> import re
>>> text = 'Hello {full_name} this is my special address named {address1}_{address2}.'
>>> re.findall(r'{[^{}]*}', text)
['{full_name}', '{address1}', '{address2}']
尝试非贪婪的比赛:
matches = re.findall(r'{.*?}', s)
You need a non-greedy quantifier: 您需要一个非贪婪的量词:
matches = re.findall(r'{.*?}', s)
Note the question mark ?
注意问号
?
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.