我有一个字符串s
,其中包含: -
Hello {full_name} this is my special address named {address1}_{address2}.
我正在尝试匹配大括号中包含的所有字符串实例。
尝试: -
matches = re.findall(r'{.*}', s)
给了我
['{full_name}', '{address1}_{address2}']
但我实际上想要检索的是
['{full_name}', '{address1}', '{address2}']
我该怎么做?
答案 0 :(得分:4)
>>> import re
>>> text = 'Hello {full_name} this is my special address named {address1}_{address2}.'
>>> re.findall(r'{[^{}]*}', text)
['{full_name}', '{address1}', '{address2}']
答案 1 :(得分:2)
尝试非贪婪的比赛:
matches = re.findall(r'{.*?}', s)
答案 2 :(得分:1)
你需要一个非贪婪的量词:
matches = re.findall(r'{.*?}', s)
请注意问号?
。