3

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}}"

Community
  • 1
  • 1
  • Where is this input HTML coming from and why exactly do you need the element texts in double curly braces? Thanks. – alecxe Feb 18 '16 at 16:09

2 Answers2

4

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

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.

Christian Stewart
  • 15,217
  • 20
  • 82
  • 139