Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除表格中的图案“;{%…%}”的;一串_Python_Regex - Fatal编程技术网

Python 删除表格中的图案“;{%…%}”的;一串

Python 删除表格中的图案“;{%…%}”的;一串,python,regex,Python,Regex,我正在解析一个文件的行,我想删除“{%”和“%}”之间的任何内容,因为这些行表示注释 更具体地说,是字符串,例如 bla{% comment %} bli {% useless %}blu 应该回来 bla bli blu 我尝试使用正则表达式,删除了所有与{%.*%}匹配的内容: import re s = 'bla{% comment %} bli {% useless %}blu' regexp = '{% .* %}' comments = re.findall(regexp, s)

我正在解析一个文件的行,我想删除“{%”和“%}”之间的任何内容,因为这些行表示注释

更具体地说,是字符串,例如

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

您应该使用并使您的正则表达式非贪婪添加

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

您需要
*?
。你的小点是

当一个操作符是贪婪的时,它会“尽其所能地”获取匹配结果,这意味着它从第一个
{%
到最后一个
%}

bla{% comment %} bli {% useless %}blu
   ^ here        ...            ^ to here
当一个操作符懒惰时会“尽可能少地”接受,并且仍然会导致匹配,这意味着它将从
{%
转到下一个
%}

最好不要显式地添加空格,因为模式不会匹配没有空格的注释:

regexp = '{%.*?%}'

这只是解释,因为它的长度是答案

惰性替代方案(不使用点。)

惰性变化(不使用星号)

这并不能解释什么。这比只回答代码要好一点。只是它没有回答这个问题。
regexp = '{%.*?%}'
{% [^\W]+ %}       
{% [^\W]* %}
{% [^\W]+? %}
{% [^\W]*? %}
{% [\w]+ %}
{% .+? %}