简体   繁体   English

Python正则表达式查找大括号的所有情况,包括大括号

[英]Python regex to find all case of curly brackets, inclusive of brackets

I would to like find and replace strings within double curly brackets, inclusive of the brackets themselves. 我想查找并替换双大括号内的字符串,包括括号本身。

For example: 例如:

<a href="#">{{hello}}</a>

should ideally return: 理想情况下应返回:

{{hello}}

I found this expression: {{(.*?)}} here 我发现这个表达式: {{(.*?)}} 这里

However this only returns text between the brackets. 但是,这仅返回括号之间的文本。 Ie. IE浏览器。 With this expression, the example above would return: "hello" , rather than "{{hello}}" 使用此表达式,上面的示例将返回: "hello" ,而不是"{{hello}}"

You can just move the ( and ) to include the brackets within the group. 您只需移动()将括号括入组中。

Try: ({{.*?}}) . 试试: ({{.*?}}) I highly recommend a regex tester for this kind of work. 我强烈推荐这种工作的正则表达式测试器

I'm assuming you're using re.findall() which only returns the contents of capturing groups, if they are present in the regex. 我假设您使用的是re.findall() ,如果正则表达式中存在捕获组的内容,则仅返回它们。

Since you don't want them, just remove the capturing parentheses: 由于您不希望使用它们,因此只需删除捕获括号即可:

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

When using re.sub() for replacing, the original regex will work just fine. 使用re.sub()进行替换时,原始正则表达式可以正常工作。

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

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