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

 

posted @   你说夕阳很美  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2023-12-04 flask + layui框体 + iframe,实现点击左侧菜单,显示不同页面
2023-12-04 layui.table组件排序问题解决:前端排序、后端排序、保留筛选条件排序
2023-12-04 pipreqs 自动找到项目的所有组件和模块版本
2023-12-04 解决flask返回中文编码问题
点击右上角即可分享
微信分享提示