[英]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.