简体   繁体   中英

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?

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']
re.findall(r"({.*?})", mystring)

让你的*非贪心。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM