Regex 正则表达式与.txt文件中的IP匹配
我需要从一个.txt文件中选择Ip地址并创建一个列表 我已经写了代码,但没有得到想要的结果。我已经阅读了与之相关的StackOverflow中发布的答案Regex 正则表达式与.txt文件中的IP匹配,regex,python-2.7,Regex,Python 2.7,我需要从一个.txt文件中选择Ip地址并创建一个列表 我已经写了代码,但没有得到想要的结果。我已经阅读了与之相关的StackOverflow中发布的答案 import sys import re def get_up_ip(): ip = [] fp = open('./output1.txt', 'r') for line in fp: if re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,
import sys
import re
def get_up_ip():
ip = []
fp = open('./output1.txt', 'r')
for line in fp:
if re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line.splitlines()[2]):
ip.append(line.split()[2])
return ip
get_up_ip()
output1.txt:
sw3# show end
----------------------------------------------------------------
Node 10 (fs-az4-10)
----------------------------------------------------------------
Legend:
s - arp O - peer-attached a - local-aged S - static
V - vpc-attached p - peer-aged M - span L - local
B - bounce H - vtep
+-----------------------------------+---------------+-----------------+--------------+-------------+
VLAN/ Encap MAC Address MAC Info/ Interface
Domain VLAN IP Address IP Info
+-----------------------------------+---------------+-----------------+--------------+-------------+
sw:swSer 143.252.78.9 tunnel165
sw:swSer 171.252.232.229 a tunnel1
sw:swSer 17.252.232.77 p tunnel1
sw:swSer 9.252.193.109 a tunnel3
apic#
所需结果:
ip = ['143.252.78.9','171.252.232.229','17.252.232.77','9.252.193.109']
['143.252.78.9', '171.252.232.229', '17.252.232.77', '9.252.193.109']
试试这个代码!
它工作得很好
import sys
import re
def get_up_ip():
ip = []
fp = open('output.txt', 'r')
f = fp.read()
obj = re.findall(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})[ ]', f)
return obj
print get_up_ip()
输出:
ip = ['143.252.78.9','171.252.232.229','17.252.232.77','9.252.193.109']
['143.252.78.9', '171.252.232.229', '17.252.232.77', '9.252.193.109']
您的regexp为我工作,只需将line.split()[2]调整为line.split[1]
import sys
import re
def get_up_ip():
ip = []
fp = open('output1.txt', 'r')
for line in fp:
if len(line.split()) > 1:
if re.match(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line.split()[1]):
ip.append(line.split()[1])
return ip
print 'Result:'
print get_up_ip()
我看到了期望的结果,但你现在得到了什么结果?