我正在处理从早期配置中收到的以下输出
['Te1/1/1', 'server', 'Ten', 'connected', 'trunk', 'full', '10G', '10Gbase-LR']
['Te1/1/2', 'desc', 'connected', 'trunk', 'full', '10G', '10Gbase-LR']
['Gi1/2/1', 'desc', 'disabled', 'routed', 'full', '1000', 'No', 'Transceiver']
['Gi2/1/2', 'disabled', 'routed', 'full', '1000', 'No', 'Transceiver']
['Te2/2/1', 'server', 'notconnect', '301', 'full', '10G', '10Gbase-LR']
['Po120', 'notconnect', 'unassigned', 'auto', 'auto']
['Po121', 'notconnect', '1', 'auto', 'auto']
我想从列表中删除任何字符串,直到找到除第一项之外的字符串“已连接”、“已禁用”或“未连接”
我尝试了以下配置:
regex_chk = re.compile("((?:not)*?connect(?:ed)*|disabled|)")
for item in items:
for i in item[1:]:
if i != regex_chk:
item.remove(i)
print(item)
结果如下:
['Te1/1/1']
['Te1/1/2']
['Gi1/2/1']
['Gi2/1/2']
['Te2/2/1']
['Po120']
['Po121']
而我希望结果是
['Te1/1/1', 'connected', 'trunk', 'full', '10G', '10Gbase-LR']
['Te1/1/2', 'connected', 'trunk', 'full', '10G', '10Gbase-LR']
['Gi1/2/1', 'disabled', 'routed', 'full', '1000', 'No', 'Transceiver']
['Gi2/1/2', 'disabled', 'routed', 'full', '1000', 'No', 'Transceiver']
['Te2/2/1', 'notconnect', '301', 'full', '10G', '10Gbase-LR']
['Po120', 'notconnect', 'unassigned', 'auto', 'auto']
['Po121', 'notconnect', '1', 'auto', 'auto']
首先,您应该更改正则表达式模式。
第二,当你有比赛时就休息一下
这个简单的模式适合我。 试试看
模式
((?:not)*?connect(?:ed)*|disabled|)
还匹配像notconnected
或notnotconnecteded
这样的字符串,并且末尾的|
使其也匹配任何其他位置您也没有在
if i != regex_chk:
中使用正则表达式,它可能类似于if not regex_chk.match(i)
但是您的数据不需要正则表达式,您可以使用startswith,因为单词都位于字符串的开头
Python demo
输出
相关问题 更多 >
编程相关推荐