Calvin Cheng
Calvin Cheng

Reputation: 36506

python regex: match to the first "}"

I have a string s containing:-

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?

Upvotes: 0

Views: 134

Answers (3)

Li-aung Yip
Li-aung Yip

Reputation: 12486

You need a non-greedy quantifier:

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

Note the question mark ?.

Upvotes: 1

robertklep
robertklep

Reputation: 203369

Try a non-greedy match:

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

Upvotes: 2

jamylak
jamylak

Reputation: 133584

>>> import re
>>> text = 'Hello {full_name} this is my special address named {address1}_{address2}.'
>>> re.findall(r'{[^{}]*}', text)
['{full_name}', '{address1}', '{address2}']

Upvotes: 4

Related Questions