从列表中过滤 IP 地址

filter IPaddress from list

我是 python 的新手 我设法使用 xlrd 从 excel sheet 中提取数据并放入列表中并删除所有 white/empty 空格

我需要从列表中提取 IP 地址或删除所有文本。我查看了条带正则表达式和模块 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']
#

您可以使用此正则表达式从列表中提取 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

您可以这样做:

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']

使用 HERE

中的正则表达式

如果您不需要验证它们看起来像好的 IP4 地址,您可以将正则表达式缩短为:

>>> 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']

纯 Python 过滤解决方案可能类似于:

>>> filter(None, [''.join([c for c in s if c in '0123456789.']) for s in  ipList])
['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']