我有一个问题,我需要从电子邮件标题的以下部分获取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。
将不胜感激。
感谢。
答案 0 :(得分:2)
(?<=\[)\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)
参见演示。
答案 1 :(得分:1)
好像你正试图获取[]
括号内的数据。
>>> 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'
OR
>>> re.findall(r'(?<![.\d])\b\d{1,3}(?:\.\d{1,3}){3}\b(?![.\d])', s)
['11.11.11.11']
答案 2 :(得分:1)
使用正则表达式
(?<=\[)\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']
答案 3 :(得分:0)
>>> 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']
答案 4 :(得分:0)
>>> f=open("file")
>>> for line in f:
... if "Received" in line:
... print line.split("]")[0].split("[")[-1]
...
11.11.11.11