python - 如何从字符串中提取IP地址

标签 python regex

我正在尝试从字符串中提取 IP 地址

import re
stri_ = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,
reject,192.168.1.1/32,reject
172.168.1.4-172.168.1.4,reject
'''
ip_addr_with_range = re.findall('([0-9+-reject]+)\,(reject)*',stri_)
ip_addr_without_range = re.findall('/([0-9\-reject]+)*',stri_)
for i in ip_addr_with_range :
      print (i[0])

我的出局

192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,reject,192.168.1.1/32
172.168.1.4-172.168.1.4

期望出局

 ip_addr_with_range
[192.168.1.1,192.168.1.2/32,192.168.1.5,192.168.1.7,192.168.1.1/32,172.168.1.4,172.168.1.4]


ip_addr_without_range
 [192.168.1.1,192.168.1.2,192.168.1.5,192.168.1.7,192.168.1.1,172.168.1.4,172.168.1.4]

最佳答案

这应该有效。

ip_addr_with_range = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}', stri_)
ip_addr_without_range = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', stri_)

关于python - 如何从字符串中提取IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58620712/

相关文章:

python - 将文本添加到矩形上

python - 如何进行时间序列向后重采样,例如从最后数据日期开始的 5 个工作日?

python - 将多个csv文件导入pandas并合并成一个DataFrame

php - 正则表达式查找以@ php开头的用户名

regex - 获取正则表达式的算法

regex - 正则表达式匹配两个单词第一次出现之间的所有内容,这两个单词都出现不止一次

带代理的 Python httplib.HTTPSConnection

Python:获取Popen实例的命令名称

Java String.replaceAll 带有命名组的反向引用

regex - CMake 正则表达式匹配