Python逐行匹配正则表达式模式
我正在使用需要逐行匹配正则表达式模式的代码 是否仍有将所有正则表达式输出放入列表的方法?我确实有一个代码草案,但我还没有弄明白。尽管仍在努力寻找解决方案Python逐行匹配正则表达式模式,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我正在使用需要逐行匹配正则表达式模式的代码 是否仍有将所有正则表达式输出放入列表的方法?我确实有一个代码草案,但我还没有弄明白。尽管仍在努力寻找解决方案 teststr = """router#sh ip bgp Status codes: s suppressed, d damped, h history, * valid, > best, i - internal, r RIB-failure, S Stale, m multipath, b
teststr = """router#sh ip bgp
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal,
r RIB-failure, S Stale, m multipath, b backup-path, x best-external
Origin codes: i - IGP, e - EGP, ? - incomplete
Network Next Hop Metric LocPrf Weight Path
*> 6.120.0.0/18 2.2.2.11 0 3111 2000 2485 43754 i
*> 6.120.0.0/17 2.2.2.11 0 3111 2000 2485 43754 i
*> 13.44.61.0/24 2.2.2.11 0 3111 4559 i
*> 13.44.62.0/24 2.2.2.11 0 3111 4559 i"""
data = []
for line in teststr:
if line !='':
word = re.search('> \d............', line)
data.append(str(word))
print (data)
谢谢我想您正在尝试搜索所有网络并保存在列表中
re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',teststr)
我认为您正在尝试搜索所有网络并将其保存在列表中
re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',teststr)
list.txt:
router#sh ip bgp
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal,
r RIB-failure, S Stale, m multipath, b backup-path, x best-external
Origin codes: i - IGP, e - EGP, ? - incomplete
Network Next Hop Metric LocPrf Weight Path
*> 6.120.0.0/18 2.2.2.11 0 3111 2000 2485 43754 i
*> 6.120.0.0/17 2.2.2.11 0 3111 2000 2485 43754 i
*> 13.44.61.0/24 2.2.2.11 0 3111 4559 i
*> 13.44.62.0/24 2.2.2.11 0 3111 4559 i
然后:
logFile = "list.txt"
with open(logFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
# network list to save the ip's
netList = []
for line in content:
if line.startswith("*>"):
netList.append(line.split(" ")[1])
print(netList)
输出:
['6.120.0.0/18', '6.120.0.0/17', '13.44.61.0/24', '13.44.62.0/24']
list.txt:
router#sh ip bgp
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal,
r RIB-failure, S Stale, m multipath, b backup-path, x best-external
Origin codes: i - IGP, e - EGP, ? - incomplete
Network Next Hop Metric LocPrf Weight Path
*> 6.120.0.0/18 2.2.2.11 0 3111 2000 2485 43754 i
*> 6.120.0.0/17 2.2.2.11 0 3111 2000 2485 43754 i
*> 13.44.61.0/24 2.2.2.11 0 3111 4559 i
*> 13.44.62.0/24 2.2.2.11 0 3111 4559 i
然后:
logFile = "list.txt"
with open(logFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
# network list to save the ip's
netList = []
for line in content:
if line.startswith("*>"):
netList.append(line.split(" ")[1])
print(netList)
输出:
['6.120.0.0/18', '6.120.0.0/17', '13.44.61.0/24', '13.44.62.0/24']
你想匹配什么?你想匹配什么?这需要更多的内容来解释为什么回答这个问题。谢谢@abdullah.cuThis需要更多的内容来解释为什么回答这个问题。谢谢@abdullah.cuThanks@user5173426hanks@user5173426