简体   繁体   中英

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

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 . Any help would be greatly appreciated.

\\b also matches a dot character, use a space instead of it:

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:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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