Python regex无法删除[%~abcd~%]之间的内容

2024-10-03 02:35:47 发布

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

我有原始HTML,正在尝试从输出字符串中删除整个块,例如[%~as..abcd~%]。使用python的re库

teststring = "Check the direction . [%~ MACRO wdwDate(date) BLOCK;
                 SET tmpdate = date.clone();
                 END ~%] Determine if both directions."
cleanM = re.compile('\[\%\~ .*? \~\%\]')
scleantext = re.sub(cleanM,'', teststring)

代码中有什么错误


Tags: the字符串redatehtmlcheckasblock
2条回答

你的模式应该是

cleanM = re.compile(r'\[\%\~ .*? \~\%\]',re.S)

.匹配除新行以外的任何字符,S允许匹配新行

您需要使用[\S\s]*而不是.*,并且可以省去编译:

import re
teststring = '''Check the direction . [%~ MACRO wdwDate(date) BLOCK;
                 SET tmpdate = date.clone();
                 END ~%] Determine if both directions.'''
scleantext = re.sub('(\[%~ [\S\s]* ~%\])', '', teststring)

print(scleantext)

相关问题 更多 >