如何使用Python在文件中搜索IP? [英] How to search for IPs in Files using Python?

查看:207
本文介绍了如何使用Python在文件中搜索IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写脚本,我需要在文件中搜索和替换IP ....

I am writing a Script in Python and I need to search and Replace IPs in a File....

任何想法如何实现?

推荐答案

正则表达式。

re.sub('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}','CENSORED_IP',data)

值得注意的是,这也匹配999.999之类的东西.999.999。如果这是一个问题,你将不得不得到一个更复杂的正则表达式。此外,这仅适用于IPv4地址。

Worthy of note, this also matches things like 999.999.999.999. If that's a problem, you will have to get a regex that is a little more complicated. Furthermore, this only works on IPv4 Addresses.

仅在有效IP上:

re.sub('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)','CENSORED_IP',data)

资料来源:正则表达式来源

这篇关于如何使用Python在文件中搜索IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆