0

I have:

data = [[u'text'],[u'element'],[u'text00']]
pattern = text
pattern2 = EL
pattern3 = 00 

Using regex I want to search and return:

text, text00 # for pattern
element      # for pattern2
text00       # for pattern3

2 Answers2

2

I think what you're looking for is any():

>>> L = ["red", "lightred", "orange red", "blue"]
>>> keyword = 'red'
>>> import re
>>> any(re.search(keyword, i) is not None for i in L)
True
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • OK, this is useful butI get: TypeError: expected string or buffer. Please note that L will be a list like this: [[[u'red']], [u'blue'], [[u'lightred']]] and keyword is user input –  Oct 03 '13 at 03:50
  • @rebHelium That's a very odd list. Using the code [here](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python/2158532#2158532), flatten the list, then use my code – TerryA Oct 03 '13 at 04:01
2
import re
data = [[u'text'], [u'element'], [u'text00']]
patterns = [u'text', u'EL', u'00']
results = []
for pattern in patterns:
    results.append([x[0] for x in data if re.search(pattern, x[0], flags=re.I)])
print  results

or, more concisely:

import re
data = [[u'text'], [u'element'], [u'text00']]
patterns = [u'text', u'EL', u'00']
results = [[x[0] for x in data if re.search(pattern, x[0], flags=re.I)] for pattern in patterns]
print  results
Josha Inglis
  • 1,018
  • 11
  • 23