2013-10-23 47 views
0

我有一個字符串列表。我試圖找到匹配正則表達式模式的列表中的所有字符串。使用正則表達式的搜索列表

我在考慮用循環/列表理解/過濾來實現。

Similar to this post. (不過,我不是很明白什麼是該職位的r.match所以我就開始單獨的線程)。

import re 
word_list = ['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1'] 
# start with letter C/D and then follow by digit 
pattern = re.compile('^[CD]\d.*') 
result_list = [] 
for word in word_list: 
    try: 
     result_list.append(re.findall(pattern, word)[0])  
    except: 
     pass 

print word_list 
print result_list 

# OUTPUT >> 
['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1'] 
['C3S3', 'D4D4'] 

誰能給我一個如何實現我的想法的一些提示使用列表解析或過濾器。

回答

2

你在找這個嗎?

In [1]: import re 

In [2]: l = ['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1'] 

In [3]: l2=filter(lambda x:re.match(r'^[CD]\d.*',x), l) 

In [4]: l 
Out[4]: ['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1'] 

In [5]: l2 
Out[5]: ['C3S3', 'D4D4'] 
+0

這就是我想要的東西。如果你可以打破Ln [3]並解釋它,那將是非常棒的! –

+0

@ B.Mr.W。你可以在這裏找到解釋:http://docs.python.org/2/library/functions.html#filter – Kent

1

如果你想要一個簡單的列表理解:

import re 
word_list = ['A1S3', 'B2B4', 'C3S3', 'D4D4', 'E5B3', 'F6D1'] 
pattern = re.compile(r'^[CD]\d') # don't need the .* to just search for pattern 

result_list = [x for x in word_list if re.search(pattern,x)] 

輸出:

['C3S3', 'D4D4']