Python regex to find all case of curly brackets, inclusive of brackets

一世执手 提交于 2021-01-28 04:50:41

问题


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. With this expression, the example above would return: "hello", rather than "{{hello}}"


回答1:


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.




回答2:


I'm assuming you're using re.findall() which only returns the contents of capturing groups, if they are present in the regex.

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.



来源:https://stackoverflow.com/questions/35485949/python-regex-to-find-all-case-of-curly-brackets-inclusive-of-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!