繁体   English   中英

python 3中的确切字符串匹配

[英]Exact string matches in python 3

我有一个清单:

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']

试图找到一个可以找到与'eth2'完全匹配的正则表达式,我不希望匹配返回'eth2.1' and eth2.2为true

这是我已经有的代码

    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')

不幸的是,这段代码找到了所有以eth2开头的字符串。 任何帮助将不胜感激。

\\b还匹配一个点字符,请使用空格代替:

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

如果要搜索像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