2014-10-30 35 views
1

我有一個問題,我需要從電子郵件標題的以下部分獲取IP地址。使用正則表達式從電子郵件標題查找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 <[email protected]>; 

我只需要輸出11.11.11.11在Python中使用正則表達式。

幫助將不勝感激。

謝謝。

回答

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 <[email protected]>;" 

re.findall(p, test_str) 

查看演示。

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

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 <[email protected]>;""" 
>>> 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'] 
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 <[email protected]>;""" 
>>> re.findall(r'(?<=\[)\d{1,3}(?:\.\d{1,3}){3}(?=\])', x) 
['11.11.11.11'] 
+0

這就像一個魅力.. – Avinash 2014-10-30 07:26:51

+0

@Avinash很高興聽到它的工作!!!。確認你喜歡的任何答案,以便其他答案對你有所幫助 – nu11p01n73R 2014-10-30 08:25:34

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 <[email protected]>;""" 
>>> re.findall(r'\[(.*)\]',a) 
['11.11.11.11'] 
0
>>> f=open("file") 
>>> for line in f: 
... if "Received" in line: 
...  print line.split("]")[0].split("[")[-1] 
... 
11.11.11.11 
相關問題