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
6
  • What are you expecting? Commented Oct 3, 2013 at 3:25
  • To find the pattern. If user enters "red" and the list is ["red", "lightred", "orange red", "blue"] then it should return true. Commented Oct 3, 2013 at 3:37
  • That's what if pattern in data: already returns Commented Oct 3, 2013 at 3:38
  • @Haidro I think OP wants "red", "lightred", "orange red" to be returned for red. Commented Oct 3, 2013 at 3:39
  • @SantoshKumar hm, thought so. Just odd how the example structure already has red in it Commented Oct 3, 2013 at 3:40

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that did it, tks!
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

2 Comments

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
@rebHelium That's a very odd list. Using the code here, flatten the list, then use my code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.