我正在解析一个文件的行,我想删除“{%”和“%}”之间的任何内容,因为这些行表示注释
更具体地说,一个字符串,例如
bla{% comment %} bli {% useless %}blu
你应该回来
bla bli blu
我尝试了正则表达式,删除了所有与{% .* %}
匹配的内容:
import re
s = 'bla{% comment %} bli {% useless %}blu'
regexp = '{% .* %}'
comments = re.findall(regexp, s)
for comment in comments:
s = s.replace(comment, '')
print s
这会产生blablu
并擦除bli
。虽然我知道它为什么会这样,但我不知道如何获得blabliblu
应该使用^{} 并使regex非贪婪地添加
?
你需要
.*?
。你的点是greedy当一个操作符是贪心的时,它会“尽可能地”得到匹配结果,这意味着它从第一个
{%
到最后一个%}
当一个操作符懒惰时,接受“尽可能少的”结果仍然匹配,这意味着它将从
{%
转到下一个%}
最好不要显式添加空格,因为没有空格的模式将不匹配注释:
这只是解释,由于长度它是作为答案
相关问题 更多 >
编程相关推荐