删除格式为“{%…%}”的模式一串

2024-10-03 13:17:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 文件字符串inimportre内容forcomment
3条回答

应该使用^{}并使regex非贪婪地添加?

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

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

regexp = '{% .*? %}'

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

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

当一个操作符懒惰时,接受“尽可能少的”结果仍然匹配,这意味着它将从{%转到下一个%}

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

regexp = '{%.*?%}'

这只是解释,由于长度它是作为答案

laziness alternative( not using dot.)

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

laziness variation(not using asterisk)

{% .+? %} 

相关问题 更多 >