删除字符串中"{%...%}"形式的模式

mim*_*imo 0 python regex

我正在解析一个文件的行,我要删除"{%"和"%}"之间的任何内容,因为它们代表注释.

更具体地说,一个字符串如

bla{% comment %} bli {% useless %}blu
Run Code Online (Sandbox Code Playgroud)

应该回来

bla bli blu
Run Code Online (Sandbox Code Playgroud)

我尝试使用正则表达式,删除匹配的所有内容{% .* %}:

import re
s = 'bla{% comment %} bli {% useless %}blu'
regexp = '{% .* %}'
comments = re.findall(regexp, s)
for comment in comments:
    s = s.replace(comment, '')
print s
Run Code Online (Sandbox Code Playgroud)

这给予blablu和删除bli.虽然我理解为什么它会像那样,但我不知道该怎么做blabliblu.

Bor*_*der 6

你需要.*?.你的点贪婪.

regexp = '{% .*? %}'
Run Code Online (Sandbox Code Playgroud)

当操作员贪婪时,"尽可能多"并且仍然会导致匹配,这意味着它从第一个{%到最后一个%}

bla{% comment %} bli {% useless %}blu
   ^ here        ...            ^ to here
Run Code Online (Sandbox Code Playgroud)

当操作员懒惰时,"尽可能少"并且仍然会导致匹配,这意味着它将从下一个{%另一个 %}.

它也可能最好不显式添加空格,因为模式不匹配没有空格的注释:

regexp = '{%.*?%}'
Run Code Online (Sandbox Code Playgroud)