简体   繁体   中英

Python search regex from variable inside a list

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

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM