Python 解析文本文档的正则表达式
我正在尝试用解析文本文档!如果和!在两者之间结束。我想有没有文字!如果!endif和它们之间的文本 例如:Python 解析文本文档的正则表达式,python,regex,Python,Regex,我正在尝试用解析文本文档!如果和!在两者之间结束。我想有没有文字!如果!endif和它们之间的文本 例如: text !if text1 !endif text2 我想让我的输出=文本+文本2+ 我尝试了类似于re.findall(r'((^(!if.*!endif))+',text)的方法。但它似乎对我不起作用。您的正则表达式应该是: ^!if$.*?^!endif$\s+ 上面说: ^ - Match the beginning of a line (because of th
text
!if
text1
!endif
text2
我想让我的输出=文本+文本2+
我尝试了类似于re.findall(r'((^(!if.*!endif))+',text)的方法。但它似乎对我不起作用。您的正则表达式应该是:
^!if$.*?^!endif$\s+
上面说:
^ - Match the beginning of a line (because of the re.M flag)
!if - Match !
$ - Match the end of a line (because of the re.M flag)
.*? - Match any number of characters (non-greedy) (includes line breaks, because of the re.S flag)
^ - Match the beginning of a line (because of the re.M flag)
!endif - Match !endif
$ - Match the end of a line (because of the re.M flag)
\s+ - Match one or more whitespace characters
因此,您应该能够像这样使用它,它用一个空字符串(nothing)替换上面所有出现的正则表达式:
这:
请注意,这明确要求!if
和!endif
在单独的行上。如果这不是一个要求,您可以从正则表达式的中间删除$
和^
锚定
^!if.*?!endif$\s+
我可以在sed方面提供帮助:
sed '/^if$/,/^endif$/ d'
以下是sed使用的算法:
阅读OP的源代码表明文本实际上在多行上。我对其进行了相应的编辑。@Karl-我明白了,谢谢您的更新。我已经更正了我的答案。我不明白您的表达式如何不会出现
语法错误,因为您的原始文本从来没有结尾撇号。@JoelCornett这只是一个打字错误。我更正了我不太确定shell脚本是否对您有用。
^!if.*?!endif$\s+
sed '/^if$/,/^endif$/ d'