Q: Remove patterns of the form "{% ... %}" in a string I am parsing lines of a file for which I want to remove anything between "{%" and "%}", as these represent comments.
More specifically, a string such as
bla{% comment %} bli {% useless %}blu

should return
bla bli blu

I have tried with a regular expression, by removing everything that was matched by {% .* %}:
import re
s = 'bla{% comment %} bli {% useless %}blu'
regexp = '{% .* %}'
comments = re.findall(regexp, s)
for comment in comments:
    s = s.replace(comment, '')
print s

This gives blablu and erases bli. While I understand why it behaves like that, I don't know how to get blabliblu.

A: You need .*?. Your dot is greedy.
regexp = '{% .*? %}'

When an operator is greedy is takes "as much as it can" and still result in a match, which means that it goes from the first {% to the last %}
bla{% comment %} bli {% useless %}blu
   ^ here        ...            ^ to here

When an operator is lazy is takes "as little as it can" and still result in a match, which means that it will go from the {% to the next %}.
Its also probably best to not explicitly add the spaces, as the pattern will not match comments without spaces:
regexp = '{%.*?%}'


A: You should use re.sub() and make you regex non-greedy adding ?.
import re
s = 'bla{% comment %} bli {% useless %}blu'
regexp = '{% .*? %}'
s = re.sub(regexp, "", s)
print(s) # bla bli blu


A: This is just explanation due to length it is as answer!

laziness alternative( not using dot.)

{% [^\W]+ %}       
{% [^\W]* %}
{% [^\W]+? %}
{% [^\W]*? %}
{% [\w]+ %}


laziness variation(not using asterisk)

{% .+? %} 

