Python search regex from variable inside a list

前提是你 提交于 2019-12-18 07:24:28

问题


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

回答1:


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



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


来源:https://stackoverflow.com/questions/19150208/python-search-regex-from-variable-inside-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!