【问题标题】:Python regex match n lines after matchPython 正则表达式匹配后匹配 n 行
【发布时间】:2019-10-21 20:39:53
【问题描述】:

我有一个在 regexr.com 上使用 pcre 可以正常工作的模式,但是当我将它与 python 一起使用时,它不匹配任何东西。 模式是:

.*(?<=RSA SHA256:).*(?:.*\n){3}.*

它与网站上的数据相匹配,但是当我在我的 python 脚本上运行它时却不匹配。 目标是匹配 Accepted publickey 和接下来的 3 行。 谢谢!

下面的脚本:

import re
Accepted_publickey=r'.*(?<=RSA SHA256:).*(?:.*\n){3}.*'
file=open('secure')
for items in file:
    re1=re.search(Accepted_publickey,items)
    if re1:
        print(re1.group())

实际数据为:

Oct 21 17:27:21 localhost sshd[19772]: Accepted publickey for vagrant from 192.168.2.140 port 54614 ssh2: RSA SHA256:uDsE4ecSD9ElWQ5Q0fdMsbqEzOe0Hszilv8xhU6dT6M
Oct 21 17:27:22 localhost sshd[19772]: pam_unix(sshd:session): session opened for user vagrant by (uid=0)
Oct 21 17:27:22 localhost sshd[19772]: User child is on pid 19774
Oct 21 17:27:22 localhost sshd[19774]: Starting session: shell on pts/2 for vagrant from 192.168.2.140 port 54614 id 0

【问题讨论】:

  • 你的实际行为是什么?

标签: regex python-3.x regex-lookarounds


【解决方案1】:

您不必使用lookbehind,您可以匹配该值。

要匹配以下 3 行,您可以切换换行符和 .* 以省略最后的 .*

^.*\bRSA SHA256:.*(?:\n.*){3}
  • ^ 字符串开始
  • .*\bRSA SHA256:.* 在字符串中匹配RSA SHA256:,前面有一个单词边界
  • (?:\n.*){3} 重复 3 次换行符,然后匹配除换行符以外的任何字符 3 次

Regex demo

在您的代码中,您可能会使用read():

import re

Accepted_publickey = r'^.*RSA SHA256:.*(?:.*\n){3}.*'
f = open('secure')
items = f.read()
re1 = re.search(Accepted_publickey, items, re.M)
if re1:
    print(re1.group())

【讨论】:

  • 谢谢你,这很有帮助,但我不知道为什么当我运行它时它不打印任何东西。该模式确实适用于正则表达式演示。
  • 我已经用re.M 更新了答案你能检查它是否有效吗?我在本地环境中运行一个名为 secure 的文件和您的示例数据,我得到了 4 行。
  • @J0876car 启用多行。您可以使用re.Mre.MULTILINEdocs.python.org/3/library/re.html#re.MULTILINE 并影响锚点的含义。
  • re2=re.findall(Accepted_publickey.strip(),items,re.M) if re2: print('\n'',''\n'.join(re2)) 和我得到我想要的。再次感谢您!
  • @J0876car 确实,如果您使用 re.findall,您将获得所有匹配项。 regex101 上还有一个代码生成器。这会使用 re.finditer regex101.com/r/Yl7cEF/1/codegen?language=python 生成示例代码
猜你喜欢
  • 1970-01-01
  • 2016-07-01
  • 2013-09-22
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
相关资源
最近更新 更多