![](/img/trans.png)
[英]Regex: how to extract only first IP address from string (in Python)
[英]How to extract the first IP address from a dictionary key “Message” and add a new key called “IP” with the extracted IP address?
所以我有一個列表,里面有我從日志文件生成的字典。 我想使用從“消息”中提取的 IP 地址創建一個名為“IP”的新密鑰
這是字典列表的示例。
[{'Date': 'Jun 29', 'Time': '03:22:22', 'PID': '13251', 'Message': 'Authentication failed from 163.27.187.39 (163.27.187.39): Permission denied in replay cache code', 'Access Type': 'Success'}
...
{'Date': 'Jun 29', 'Time': '03:22:22', 'PID': '13263', 'Message': 'connection from 61.74.96.178 () at Wed Jun 29 03:22:22 2005', 'Access Type': 'Success'}]
我想過使用正則表達式,但我收到一個錯誤,說我的字典在迭代期間改變了大小。
for Dict in data:
for k,v in Dict.items():
if k == 'Message':
re.findall(r"[0-9]+(?:\.[0-9]+){3}\s", v)
Dict["host/IP address"] = re.findall(r"[0-9]+(?:\.[0-9]+){3}\s", v)
else:
Dict["host/IP address"] = ""
print(Dict)
您不需要遍歷字典,因為您知道密鑰,只需從密鑰Message
的 IP 創建新的。
\s
,因為你不想要空間r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}
更好的正則表達式檢查數字組的長度為[1-3]
[0]
從Message
獲取第一個 IP ,如果您想要找到所有 IP 的列表,請將其刪除如果沒有 IP,則應先計算 IP,然后添加有關findall
結果的映射
for value in data:
ips = re.findall(r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}", value['Message'])
if ips:
value["host/IP address"] = ips[0]
如果您想在沒有 IP 的情況下放置空字符串
for value in data:
ips = re.findall(r"[0-9]{1,3}(?:\.[0-9]{1,3}){3}", value['Message'])
value["host/IP address"] = ips[0] if ips else ""
與[0]
: 'host/IP address': '163.27.187.39'
沒有[0]
: 'host/IP address': ['163.27.187.39', '163.27.187.39']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.