![](/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.