Reputation: 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.
Upvotes: 0
Views: 1602
Reputation: 5281
You don't need regular expressions for this.
words=[word for word in listy if 'eth2' in word]
Upvotes: 0
Reputation: 2087
\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')
Upvotes: 2