SamuelRM
SamuelRM

Reputation: 13

Python - Match substring occurrences between { } with regex

I'm trying to search for one or more occurrences of a variable substring between two selectors "{" and "}" using regex. If it finds more than one, the output should be a list.

Here is an example of string :

mystring = "foofoofoo{something}{anything}foofoofoo"

This is the regex I use :

re.findall(r"^.*(\{.*\}).*$", mystring)

but it gives me the following output : {anything}

I've tried with r"(\{.*\})" and it returns me {something}{anything} which is almost good except it's not a list.

Any idea?

Upvotes: 1

Views: 302

Answers (2)

anubhava
anubhava

Reputation: 785286

Remove anchors and .* from your regex to allow it to just capture from { to }:

>>> mystring = "foofoofoo{something}{anything}foofoofoo";
>>> re.findall(r"(\{[^}]*\})", mystring);
['{something}', '{anything}']

To skip { and } from matches, use captured groups:

>>> re.findall(r"\{([^}]*)\}", mystring);
['something', 'anything']

Upvotes: 2

vks
vks

Reputation: 67968

re.findall(r"({.*?})", mystring)

Make your * non greedy.

Upvotes: 1

Related Questions