I have a list of strings. And I try to find the all strings inside that list who match a regular expression pattern.
I am thinking about use for loop/ list comprehension/ filter to implement.
Similar to this post. (However, I can not quite understand what is the r.match in that post so I started a separate thread.)
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']
Can anyone give me some hints of how to implement my idea using either list comprehensions or filter.