Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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

like image 214
Ronald Wichhart Avatar asked Jan 26 '26 18:01

Ronald Wichhart


1 Answers

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.

like image 168
Tim Pietzcker Avatar answered Jan 28 '26 06:01

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!