[英]Match string exactly from list of strings
I have a list of a device's port numbers that I want to match against but I don't want duplicates and it needs to match exactly. 我有一个要匹配的设备端口号的列表,但我不想重复,它需要完全匹配。
Here's an example of the list: 这是列表的示例:
port_list = ['port 1.1', 'port 1.2', 'port 1.3', 'port 1.4', 'port 1.5',
'port 1.6', 'port 1.7', 'port 1.8', 'port 1.9', 'port 1.10','port 1.11',
'port 1.12', 'port 1.13', 'port 1.14', 'port 1.15', 'port 1.16', 'port 1.17',
'port 1.18', 'port 1.19', 'port 1.20', 'port 1.21', 'port 1.22','port 1.23',
'port 1.24']
I found this code that works except for when I have say port 1.23 it matches the correct port but also 1.2 or for port 1.16 I also get a match for port 1.1. 我发现此代码有效,除了当我说端口1.23匹配正确的端口但也匹配1.2或端口1.16时,我也获得了端口1.1的匹配项。
matches = {x for x in port_list if x in output}
This is the output I pull the port from in an earlier part of the script 这是我在脚本的较早部分中从中拉出端口的输出
LAB-5150-MES1.NMD*> config search string "virtual-switch ethernet add"
virtual-switch ethernet add vs 022NMD001111BL port 1.20 vlan 4
virtual-switch ethernet add vs 022NMD002222BL port 1.21 vlan 20
virtual-switch ethernet add vs 022NMD003333BL port 1.23 vlan 452
Then here's what I'm trying to accomplish with pulling the port from above but it's matching on that extra port. 然后,这就是我要尝试从上方拉出端口,但在该额外端口上匹配的内容。
LAB-5150-MES1.NMD*> lldp set port 1.2 mode tx-rx notification off
LAB-5150-MES1.NMD*> lldp set port 1.20 mode tx-rx notification off
LAB-5150-MES1.NMD*> lldp set port 1.23 mode tx-rx notification off
LAB-5150-MES1.NMD*> lldp set port 1.21 mode tx-rx notification off
output
must be a string, right? output
必须是字符串,对吗? That's why 'port 1.1' in output
is True
when it's actually 'port 1.16'
. 这就是为什么'port 1.1' in output
实际上是'port 1.16'
时为True
的原因。 So you could simply divide it in a list and check if the number of the port is in it: 因此,您可以简单地将其划分为一个列表,然后检查其中是否包含端口号:
matches = {x for x in port_list if x.split()[1] in output.split()}
No need to use regex ;) 无需使用正则表达式;)
Edit: x.split()
divides the string in a list. 编辑: x.split()
将字符串划分为列表。 Each division is on a space. 每个分区都在一个空间上。 So the result of it is ['port', '1.16'
]. 因此,结果为['port', '1.16'
]。 We use the [1]
index notation to specify the object on index 1 (python index start on 0) - '1.16'
. 我们使用[1]
索引符号来指定索引1上的对象(python索引从0开始)- '1.16'
。 That way, we're checking if the number is on the list of words on output
. 这样,我们正在检查数字是否在output
的单词列表上。
你可以做
matches = {x for x in port_list if x == output}
With the in
operator you're using substring match, which is why when output
contains port 1.23
, it also matches port 1.2
. 通过in
运算符,您正在使用子字符串匹配,这就是为什么当output
包含port 1.23
,它还匹配port 1.2
。 In this case you should use regex to make sure that the match occurs only on word boundaries. 在这种情况下,应使用正则表达式确保匹配仅在单词边界上发生。
import re
matches = re.findall('\b(?:%s)\b' % '|'.join(port_list), output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.