0

我有一个字符串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}']

我怎样才能做到这一点?

4

3 回答 3

4
>>> import re
>>> text = 'Hello {full_name} this is my special address named {address1}_{address2}.'
>>> re.findall(r'{[^{}]*}', text)
['{full_name}', '{address1}', '{address2}']
于 2013-04-19T08:22:15.853 回答
2

尝试非贪婪匹配:

matches = re.findall(r'{.*?}', s)
于 2013-04-19T08:22:30.237 回答
1

你需要一个非贪婪的量词:

matches = re.findall(r'{.*?}', s)

注意问号?

于 2013-04-19T08:22:34.083 回答