2015-11-07 18 views
0

我正在解析要为其删除“{%”和“%}”之间的任何文件的行,因为它们代表注释。在字符串中删除表格“{%...%}”的模式

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

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

回答

2

你应该使用re.sub()并使你的正则表达式非贪心添加?

import re 
s = 'bla{% comment %} bli {% useless %}blu' 
regexp = '{% .*? %}' 
s = re.sub(regexp, "", s) 
print(s) # bla bli blu 
6

您需要.*?。你的点是greedy

regexp = '{% .*? %}' 

当操作员是贪婪是采取“多,因为它可以”,仍然导致匹配,这意味着它从第一{%进入到最后%}

bla{% comment %} bli {% useless %}blu 
^here  ...   ^to here 

当运营商是懒惰是“尽可能少”,仍然会导致匹配,这意味着它将从{%下一个%}

它也可能是最好的不明确增加的空间,因为该模式将不无空格相匹配的评论:

regexp = '{%.*?%}' 
0

这只是解释由于它的长度是答案!

懒惰替代(不使用点。)

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

懒惰变化(不使用星号)

{% .+? %} 
+0

这并没有真正_explain_任何东西。这比仅有代码的答案好一点。除了它不回答这个问题。 –