正则表达式匹配段落的所有匹配项

2024-09-28 23:09:06 发布

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

语言:python

我正在尝试匹配此段落的所有匹配项,并将它们从文件中删除。你知道吗

我不知道该怎么做正则表达式。你知道吗

正则表达式,那不行

^#--- Maintenance ---#[\s\S]*[^#--- Maintenance ---#]

代码是什么样子的

#--- Maintenance ---#
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /home/fuelvnga/public_html/.htpasswd
Require valid-user
#--- Maintenance ---#

fsadfdsaf
dsaf
dsaf
sdaf
sda
fsa
f

#--- Maintenance ---#
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /home/fuelvnga/public_html/.htpasswd
Require valid-user
#--- Maintenance ---#


sdf safd sad

      #--- Maintenance ---#
      AuthType Basic
      AuthName "Restricted Content"
      AuthUserFile /home/fuelvnga/public_html/.htpasswd
      Require valid-user
      #--- Maintenance ---#

我需要下面的所有实例突出显示,即使它有压痕和其他奇怪的事情。你知道吗

我想在评论上使用regex,因为中间的内容可能会更改

#--- Maintenance ---#
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /home/fuelvnga/public_html/.htpasswd
Require valid-user
#--- Maintenance ---#

Tags: homebasichtmlrequiremaintenancecontentpublicrestricted
1条回答
网友
1楼 · 发布于 2024-09-28 23:09:06

使用

re.sub(r"# - Maintenance  -#(?:.*?)# - Maintenance  -#", "",text,0, flags=re.M|re.S)

这将用""替换匹配项。匹配是在注释# - Maintenance -## - Maintenance -#以及两者之间的任何字符上以非贪婪的方式开始/停止的。你知道吗

诀窍是给标志re.DOTALL(short:re.S)使点也匹配新行。非贪心很重要,它只匹配两个注释,而不是跨越第一个注释开始和最后一个注释结束之间的所有文本。你知道吗

在代码中,我保留了multiline标志,但这个正则表达式不需要它。你知道吗

import re

text = """
# - Maintenance  -#
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /home/fuelvnga/public_html/.htpasswd
Require valid-user
# - Maintenance  -#

fsadfdsaf
dsaf
dsaf
sdaf
sda
fsa
f

# - Maintenance  -#
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /home/fuelvnga/public_html/.htpasswd
Require valid-user
# - Maintenance  -#


sdf safd sad

      # - Maintenance  -#
      AuthType Basic
      AuthName "Restricted Content"
      AuthUserFile /home/fuelvnga/public_html/.htpasswd
      Require valid-user
      # - Maintenance  -#

"""

matsch = re.sub(r"# - Maintenance  -#(?:.*?)# - Maintenance  -#", "",text,0, flags=re.M|re.S)
print (matsch)

u使用一个非贪婪匹配,它应该匹配两个维护块之间的任何内容。你知道吗

输出:

fsadfdsaf
dsaf
dsaf
sdaf
sda
fsa
f




sdf safd sad

相关问题 更多 >