简体   繁体   English

Python - 匹配{}与正则表达式之间的子字符串出现

[英]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} 但它给了我以下输出: {anything}

I've tried with r"(\\{.*\\})" and it returns me {something}{anything} which is almost good except it's not a list. 我试过用r"(\\{.*\\})"并且它返回给我{something}{anything}这几乎是好的,除了它不是列表。

Any idea? 任何想法?

Remove anchors and .* from your regex to allow it to just capture from { to } : 从正则表达式中删除锚点和.*以允许它从{ 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)

让你的*非贪心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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