简体   繁体   English

Python - 显式匹配字符串中的字符串

[英]Python - matching a string within a string explicitly

I am trying to match specific router interfaces.我正在尝试匹配特定的路由器接口。 However, I am finding the below confusing, when searching for specific interface numbers, it is matching on the first condition, when i think it should be matching on the second condition:但是,我发现以下内容令人困惑,在搜索特定接口编号时,它在第一个条件下匹配,而我认为它应该在第二个条件下匹配:

string = ["TenGigE0/0/0/0.12", "TenGigE0/0/0/1.46", "TenGigE0/0/0/15.55"]

for item in string:
    if 'TenGigE0/0/0/0' in item or 'TenGigE0/0/0/1' in item:
        print("Yes")
    elif 'TenGigE0/0/0/15' in item:
        print("cool")

Output is: Output 是:

Yes
Yes
Yes

How can i fix this?我怎样才能解决这个问题?

Change the if-statements around:更改 if 语句:

string = ["TenGigE0/0/0/0.12", "TenGigE0/0/0/1.46", "TenGigE0/0/0/15.55"]

for item in string:
    if 'TenGigE0/0/0/15' in item:
        print("cool")
    elif ('TenGigE0/0/0/0' in item) or ('TenGigE0/0/0/1' in item):
        print("Yes")

Will get you:会给你:

Yes
Yes
cool

Since TenGigE0/0/0/15 contains TenGigE0/0/0/1 too, and if you check for TenGigE0/0/0/1 before checking for TenGigE0/0/0/15 the first if-statement results in True由于TenGigE0/0/0/15也包含TenGigE0/0/0/1 ,如果您在检查TenGigE0/0/0/15 TenGigE0/0/0/1则第一个 if 语句结果为 True

Let's visualise this:让我们想象一下:

  • 'TenGigE0/0/0/0' in 'TenGigE0/0/0/0.12' is true, because 'TenGigE0/0/0/0' is a substring of 'TenGigE0/0/0/0.12' : 'TenGigE0/0/0/0' 'TenGigE0/0/0/0.12'中的 'TenGigE0/0/0/0' 为真,因为'TenGigE0/0/0/0''TenGigE0/0/0/0.12'

     TenGigE0/0/0/0.12 TenGigE0/0/0/0
  • 'TenGigE0/0/0/1' in 'TenGigE0/0/0/1.46' is true, because 'TenGigE0/0/0/1' is a substring of 'TenGigE0/0/0/1.46' : 'TenGigE0/0/0/1' 'TenGigE0/0/0/1.46'中的 'TenGigE0/0/0/1' 为真,因为'TenGigE0/0/0/1''TenGigE0/0/0/1.46'

     TenGigE0/0/0/1.46 TenGigE0/0/0/1
  • Same for 'TenGigE0/0/0/15.55' : 'TenGigE0/0/0/15.55'相同:

     TenGigE0/0/0/15.55 TenGigE0/0/0/1

if statement executes the code after the first condition that is True , so even though 'TenGigE0/0/0/15' in 'TenGigE0/0/0/15.55' is True, 'TenGigE0/0/0/1' in 'TenGigE0/0/0/15.55' was first , so that's what got executed. if语句在第一个条件为True之后执行代码,因此即使'TenGigE0/0/0/15' in 'TenGigE0/0/0/15.55'为 True, 'TenGigE0/0/0/1' in 'TenGigE0/0/0/15.55'first ,所以这就是被执行的。

As already mentioned in other answers, '/1' is a substring of '/15' .正如其他答案中已经提到的, '/1''/15'的 substring 。

Another solution is to use regex with a word bound \b and a group for '0' OR '1' :另一种解决方案是使用带有单词绑定\b正则表达式和一个用于'0' OR '1'组:

import re

string = ["TenGigE0/0/0/0.12", "TenGigE0/0/0/1.46", "TenGigE0/0/0/15.55"]
for item in string:
    if re.match(r'TenGigE0/0/0/(0|1)\b', item):
        print("Yes")
    elif re.match(r'TenGigE0/0/0/15\b', item):
        print("cool")

Output: Output:

Yes
Yes
cool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM