Python 利用正则获取一段文本里的ip
import re # 正则表达式匹配 IP 地址 ip_pattern = r'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' def find_ips(text): return re.findall(ip_pattern, text) # 测试文本 text = """ Here are some IP addresses: 192.168.1.1, 255.255.255.255, 256.256.256.256, and 123.45.67.89. Another one: 10.0.0.1. Invalid ones: 999.999.999.999, 300.300.300.300. """ # 查找文本中的所有 IP 地址 ips = find_ips(text) # 输出所有找到的 IP 地址 for ip in ips: print(ip)
结果:
D:\miniconda3\python.exe D:\gitlab\test_demo\3333.py 192.168.1.1 255.255.255.255 123.45.67.89 10.0.0.1