【问题标题】:USING Regular Expressions to Find IP Address from Email Header使用正则表达式从电子邮件标头中查找 IP 地址
【发布时间】:2014-12-26 02:56:13
【问题描述】:

我有一个问题,我需要从电子邮件标题的以下部分获取 IP 地址。

Received: from smtprelay.b.mail.com (smtprelay0225.b.mail.com. [11.11.11.11])
    by mx.google.com with ESMTP id g7si12282480pat.225.2014.07.26.06.53.24
    for <a@gmail.com>;

我只需要在 python 中使用正则表达式输出 11.11.11.11。

我们将不胜感激。

谢谢。

【问题讨论】:

    标签: python regex email


    【解决方案1】:
    (?<=\[)\d+(?:\.\d+){3}(?=\])
    

    试试这个。使用re.findall

    import re
    p = re.compile(ur'(?<=\[)\d+(?:\.\d+){3}(?=\])')
    test_str = u"Received: from smtprelay.b.mail.com (smtprelay0225.b.mail.com. [11.11.11.11])\n by mx.google.com with ESMTP id g7si12282480pat.225.2014.07.26.06.53.24\n for <a@gmail.com>;"
    
    re.findall(p, test_str)
    

    查看演示。

    http://regex101.com/r/gT6kI4/10

    【讨论】:

      【解决方案2】:

      使用正则表达式

      (?<=\[)\d{1,3}(?:\.\d{1,3}){3}(?=\])
      

      提取ip

      查看正则表达式的工作原理:http://regex101.com/r/lI0rU3/1

      x="""Received: from smtprelay.b.mail.com (smtprelay0225.b.mail.com. [11.11.11.11])
      ...     by mx.google.com with ESMTP id g7si12282480pat.225.2014.07.26.06.53.24
      ...     for <a@gmail.com>;"""
      >>> re.findall(r'(?<=\[)\d{1,3}(?:\.\d{1,3}){3}(?=\])', x)
      ['11.11.11.11']
      

      【讨论】:

      • @Avinash 很高兴听到它起作用了!!!。请接受您喜欢的任何答案,以便对其他人有用,谢谢
      【解决方案3】:

      您似乎正在尝试获取存在于[] 括号内的数据。

      >>> import re
      >>> s = """Received: from smtprelay.b.mail.com (smtprelay0225.b.mail.com. [11.11.11.11])
      ...     by mx.google.com with ESMTP id g7si12282480pat.225.2014.07.26.06.53.24
      ...     for <a@gmail.com>;"""
      >>> re.search(r'(?<=\[)[^\[\]]*(?=\])', s).group()
      '11.11.11.11'
      

      >>> re.findall(r'(?<![.\d])\b\d{1,3}(?:\.\d{1,3}){3}\b(?![.\d])', s)
      ['11.11.11.11']
      

      【讨论】:

        【解决方案4】:
        >>> import re
        >>> a="""from smtprelay.b.mail.com (smtprelay0225.b.mail.com. [11.11.11.11])
        ...     by mx.google.com with ESMTP id g7si12282480pat.225.2014.07.26.06.53.24
        ...     for <a@gmail.com>;"""
        >>> re.findall(r'\[(.*)\]',a)
        ['11.11.11.11']
        

        【讨论】:

          【解决方案5】:
          >>> f=open("file")
          >>> for line in f:
          ...   if "Received" in line:
          ...     print line.split("]")[0].split("[")[-1]
          ...
          11.11.11.11
          

          【讨论】:

            猜你喜欢
            • 2012-12-26
            • 2011-12-28
            • 2013-04-09
            • 2013-08-09
            • 2011-08-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多