我是python的新手我设法使用xlrd从excel表中提取数据并放入列表并删除所有白/空格
我需要从列表中提取IP地址或删除所有文本。我看过strip regex和模块的IP地址但看起来不知所措,请帮我找一个解决方案。
ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
#
答案 0 :(得分:1)
您可以使用此正则表达式从列表中提取IP。
import re
ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
IP = []
for element in ipList:
ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', element)
if len(ip) > 0:
IP.append(ip)
print IP
答案 1 :(得分:1)
您可以执行以下操作:
vim
使用HERE
中的正则表达式如果您不需要验证它们看起来像是好的IP4地址,您可以将正则表达式缩短为:
import re
pat=re.compile(r'''\b((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]?))\b''', re.X)
>>> [m.group(1) for s in ipList for m in pat.finditer(s)]
['10.100.33.131', '10.100.33.132', '10.100.33.133', '10.100.33.134', '10.100.33.148', '10.100.33.149', '10.100.33.150']
纯Python过滤器解决方案可能类似于:
>>> pat=re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')
>>> [m.group(0) for s in ipList for m in pat.finditer(s)]
['10.100.33.131', '10.100.33.132', '10.100.33.133', '10.100.33.134', '10.100.33.148', '10.100.33.149', '10.100.33.150']