首页 > 解决方案 > 匹配以相同未知字符开头和结尾的多行字符串

问题描述

正则表达式匹配以 'banner ......' 开头的多行字符串,其中 x 是从正则表达式本身提取的

r'banner (\^|\$)(.*\n)*(\^|\$)'

将有助于 'banner ^ ........ ^' 或 'banner $ .. $' 但如果我不知道这个角色是什么并且希望它成为之后的角色怎么办'横幅'

我有一个解决方法,我捕获这个未知字符,然后在第二个正则表达式中使用它,但是有没有可能或更好的方法来做到这一点。

示例文本

banner ^

------ WARNING  ---------------------------------------------------------
This equipment is the property of XYZ.
Any unauthorised connection attempt is prohibited and will result
in criminal prosecution under applicable criminal laws.
--------------------------------------------------------------------------
^

或者

banner $
      _____________________________
     | Unauthorized access to this |
     | system is forbidden and     |
     | subject to prosecution.     |
     | All actions performed on    |
     | this device are logged.     |
      -----------------------------
 .       .
 \`-"'"-'/
  } 6 6 {
 =.  Y  ,=
   /^^^\  .
  /     \  )
 (  )-(  )/
  ""   ""
$

但请记住字符 $ / ^ 是未知的干杯

标签: pythonregex

解决方案


您正在寻找反向引用。尝试这个:

r'banner (\S)(.*\n)*(\1)'

\1第一个捕获组的反向引用在哪里。\S将匹配除空格以外的任何内容。如果只想匹配符号,可以使用[^\w\s]代替\S.

但是,此正则表达式与您的示例不匹配,banner ^ ........ ^因为该字符串不包含换行符。如果您想匹配字符或换行符的任何组合,而不是绝对需要换行符,您可以使用:

r'banner (\S)[\s\S]*(\1)'

演示


推荐阅读