Python从列表中的变量中搜索正则表达式

时间:2013-10-03 03:24:17

标签: python regex list variables search

我有:

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

使用正则表达式我想搜索并返回:

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

2 个答案:

答案 0 :(得分:2)

我认为你要找的是any()

>>> L = ["red", "lightred", "orange red", "blue"]
>>> keyword = 'red'
>>> import re
>>> any(re.search(keyword, i) is not None for i in L)
True

答案 1 :(得分: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

或更简洁:

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