简体   繁体   English

python 3中的确切字符串匹配

[英]Exact string matches in python 3

I have a list: 我有一个清单:

listy = ['{eth0 blah', '{eth1 blah blah', '{eth2 blah blah', '{eth2.1 blah blah', '{eth2.2 blah blah', '{wl0 blah blah', '{wl0.1 blah blah', '{wl1 blah blah', '{wl1.1 blah blah']

Trying to find a regular expression which can find the exact match for say 'eth2' , I do not want the match to return 'eth2.1' and eth2.2 as true 试图找到一个可以找到与'eth2'完全匹配的正则表达式,我不希望匹配返回'eth2.1' and eth2.2为true

this is the code which i have already 这是我已经有的代码

    listy = ['{eth0 blah', '{eth1 blah blah', '{eth2 blah blah', '{eth2.1 blah blah', '{eth2.2 blah blah', '{wl0 blah blah', '{wl0.1 blah blah', '{wl1 blah blah', '{wl1.1 blah blah

        for i in listy:
            if re.match(r'eth2\b',i):
            #{do something}             
            print('found')
        else:
            #{do something else}     
            print('not found')

This code unfortunately finds all strings that starts with eth2 . 不幸的是,这段代码找到了所有以eth2开头的字符串。 Any help would be greatly appreciated. 任何帮助将不胜感激。

\\b also matches a dot character, use a space instead of it: \\b还匹配一个点字符,请使用空格代替:

for elem in listy:
    if re.search('eth2 ', elem):
        print('found')
    else:
        print('not found')

If you are searching for a simple substring like eth2 , you don't need a regular expression, you can use find method: 如果要搜索像eth2这样的简单子字符串,则不需要正则表达式,则可以使用find方法:

for elem in listy:
    if elem.find('eth2 ') != -1:
        print('found')
    else:
        print('not found')

您不需要为此使用正则表达式。

words=[word for word in listy if 'eth2' in word]

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

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