【问题标题】:Python regex to pull FQDN from syslog serverPython 正则表达式从系统日志服务器中提取 FQDN
【发布时间】:2010-12-17 16:14:53
【问题描述】:

我正在尝试构建一个正则表达式来解析我们的系统日志。我被要求对使用该服务的每台服务器进行说明。我写了一个简单的正则表达式来提取 FQDN,但它似乎消耗了太多的行...

>>> string = "2010-12-13T00:00:02-05:00 <local3.info> suba1.suba2.example.com named[29959]: client 192.168.11.53#54608: query: subb1.subb2.example.com"
>>> regex = re.compile("\s.*?\.example\.com ")
>>> r = regex.search(string)
>>> r
<_sre.SRE_Match object at 0x896dae0bbf9e6bf0>

# Run findall
>>> regex.findall(string)
[u' <local3.info> suba1.suba2.example.com ', u' client 192.168.11.53#54608: query: subb1.subb2.example.com ']

正如您所见,带有 .* 的 findall 太通用了,正则表达式最终消耗了很多。

【问题讨论】:

    标签: python regex syslog fqdn


    【解决方案1】:

    \s 替换为\b 并将.*? 替换为\S 即可。

    >>> regex = re.compile(r'\b\S*\.example\.com')
    >>> regex.findall(string)
    [u'suba1.suba2.example.com', u'subb1.subb2.example.com']
    

    【讨论】:

      【解决方案2】:

      正则表达式

      r"query: ([\w\.]+)"
      

      将从 [...] 查询中获取结尾,然后您可以使用未命名的组查找来为您提供域名。

      如果这不是您需要的输出,您能否详细说明所需的输出(作为数据结构。我对此进行了猜测)。

      python 代码可能如下所示:

      match = re.search(r"query: ([\w.]+)", string, re.IGNORECASE | re.MULTILINE)
      if match:
          result = match.group(1)
      else:
          result = ""
      

      结果将包含

      subb1.subb2.example.com
      

      【讨论】:

        【解决方案3】:

        尝试使用:

        regex = re.compile("\s\S*?\.example\.com ")
        

        【讨论】:

          【解决方案4】:
          #!/usr/bin/env python
          
          import re
          
          s = """2010-12-13T00:00:02-05:00 <local3.info> 
              suba1.suba2.example.com named[29959]: 
              client 192.168.11.53#54608: query: subb1.subb2.example.com"""
          
          pattern = re.compile("[\S.]+.example.com")
          
          print pattern.findall(s)
          # => ['suba1.suba2.example.com', 'subb1.subb2.example.com']
          

          【讨论】:

          • 感谢您的回答,我忘记了 \S ...这非常适合空格分隔线。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-13
          • 1970-01-01
          相关资源
          最近更新 更多