【问题标题】:Python : Regex search on a file, and another regex in the next linePython:对文件进行正则表达式搜索,并在下一行中搜索另一个正则表达式
【发布时间】:2014-12-24 07:12:08
【问题描述】:

我正在尝试在日志文件的每一行中搜索特定字符串,如果匹配,我需要能够从该特定错误中获取主机信息。

考虑以下日志条目:

05-05-2014 00:02:02,771 [HttpProxyServer-thread-1314] ERROR fd - Empty user name specified in NTLM authentication. Prompting for auth again.
Host=tools.google.com, Port=80, Client ip=/10.253.168.128, port=37271, User-Agent: Google Update/1.3.23.9;winhttp;cup-ecdsa
05-05-2014 00:02:02,771 [HttpProxyServer-thread-2156] ERROR fd - Empty user name specified in NTLM authentication. Prompting for auth again.
Host=tools.google.com, Port=80, Client ip=/10.253.168.148, port=37273, User-Agent: Google Update/1.3.23.9;winhttp;cup-ecdsa
05-05-2014 00:02:02,802 [HttpProxyServer-thread-604] ERROR fd - Empty user name specified in NTLM authentication. Prompting for auth again.
Host=tools.google.com, Port=80, Client ip=/10.253.168.92, port=37280, User-Agent: Google Update/1.3.23.9;winhttp;cup

这是我的代码:

for line in log_file:

   if bool(re.search( r'Empty user name specified in NTLM authentication. Prompting for auth again.', line)):

   host = re.search(r'Host=(\D+.\D+.\D+,)', line).group(1)

问题是主机信息与错误不在同一行。它在下一行。我如何让 re.search(r'Host=(\D+.\D+.\D+,)', line).group(1) 在“line”当前所在的下一行中搜索?

【问题讨论】:

  • 读取整个文件有什么问题?
  • @AvinashRaj,也许,巨大的日志文件不需要舒适地放在内存中......

标签: python regex


【解决方案1】:

只需插入一个

line = next(log_file)

在您当前在 for 循环中的两个语句之间。

【讨论】:

    【解决方案2】:

    试试这个:

    >>> import re
    >>> fp = open('log_file')
    >>> line = fp.readline()
    >>> while line:
    ...    if 'Empty user name specified in NTLM authentication. Prompting for auth again.' in line:
    ...        host = re.search(r'Host=(\D+.\D+.\D+,)', fp.readline()).group(1)
    ...        #                                        ^^^^^^^^^^^^^^  
    ...        #                              this makes re search in the next line 
    ...        print host
    ...    line = fp.readline()
    ... 
    tools.google.com,
    tools.google.com,
    tools.google.com,
    

    【讨论】:

    • 伊尔沙德!工作就像一个怪异的魅力!但是“行”的内容是如何变成下一行的呢? While 语句会发生这种情况吗?
    • 查看第一行在while之外读取。现在,如果这一行包含 Empty user .... auth again.re 在下一行使用 fp.readline() in host = re.search(r'Host=(\D+.\D+.\D+,)', fp.readline()).group(1) 搜索。在while 中的最后一行代码之后,即line = fp.readline() 读取下一行并再次使用while
    【解决方案3】:

    要么编写一个匹配 2 个连续行的正则表达式,您可以从中提取每行的主机信息,然后循环匹配而不是逐行读取文件,或者添加一个在行匹配时设置的标志错误,如果为给定行设置了该标志,则提取主机信息并重置标志,而不是测试错误。

    【讨论】:

      猜你喜欢
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多