Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.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,我正在尝试用解析文本文档!如果和!在两者之间结束。我想有没有文字!如果!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

我正在尝试用解析文本文档!如果和!在两者之间结束。我想有没有文字!如果!endif和它们之间的文本

例如:

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使用的算法:

  • 将变量match设置为False
  • 读下一行
  • 检查行是否等于“if”。如果是,请将变量match设置为True
  • 如果match==True,则检查当前行是否=='endif'。 如果是,则设置match=False并删除当前行[并跳到0]
  • 打印当前行
  • 如果不是EOF,则跳到1

  • 阅读OP的源代码表明文本实际上在多行上。我对其进行了相应的编辑。@Karl-我明白了,谢谢您的更新。我已经更正了我的答案。我不明白您的表达式如何不会出现
    语法错误,因为您的原始文本从来没有结尾撇号。@JoelCornett这只是一个打字错误。我更正了我不太确定shell脚本是否对您有用。
    
    ^!if.*?!endif$\s+
    
    sed '/^if$/,/^endif$/ d'