terry433iid
terry433iid

Reputation: 19

how to compare lists whose elements are regular expressions in Python?

I wish to compare two lists, one list has ordinary data and the second has regular expressions and return a match

e.g.

list1 = ['linux','6.0.1','mysql','5','abcd1234']

list2 = ['linux.*','6.*','mysql|python|gvim','5|6','abcd1234|efgh5678|ijkl91011']

I want to iterate over list1 with the regular expressions in list2 for a match (which in the case above would be true)

Or is there a better way to go rather than lists? if/elif is possible but messy

Upvotes: 1

Views: 1884

Answers (1)

sundar nataraj
sundar nataraj

Reputation: 8702

to find which expression matched which word you can try as below

list1 = ['linux','6.0.1','mysql','5','abcd1234']    
list2 = ['linux.*','6.*','mysql|python|gvim','5|6','abcd1234|efgh5678|ijkl91011']

import re    
print {i:j  for j in list1 for i in list2 if re.match(i,j)}

#output {'mysql|python|gvim': 'mysql', 'abcd1234|efgh5678|ijkl91011': 'abcd1234', '5|6': '5', 'linux.*': 'linux', '6.*': '6.0.1'}

other way if two or more string matches

list1 = ['linux','6.0.2','6.0.1','mysql','5','abcd1234']

list2 = ['linux.*','6.*','mysql|python|gvim','5|6','abcd1234|efgh5678|ijkl91011']

import re

print {i:[j  for j in list1 if re.match(i,j)] for i in list2 }

#output {
  'mysql|python|gvim': ['mysql'], 
  'abcd1234|efgh5678|ijkl91011': ['abcd1234'], 
  '5|6': ['6.0.2', '6.0.1', '5'], 
  'linux.*': ['linux'], 
   '6.*': ['6.0.2', '6.0.1']}

if pair wise

list1 = ['linux','6.0.1','mysql','5','abcd1234']

list2 = ['linux.*','6.*','mysql|python|gvim','5|6','abcd1234|efgh5678|ijkl91011']

import re

print {j:i for i,j in zip(list1,list2) if re.match(j,i) }

Upvotes: 5

Related Questions