问题
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