0

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.

Community
  • 1
  • 1
B.Mr.W.
  • 18,910
  • 35
  • 114
  • 178

2 Answers2

2

are you looking for this?

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']
Kent
  • 189,393
  • 32
  • 233
  • 301
  • That is exactly what I want. If you can break Ln [3] and explain it a bit that would be awesome! – B.Mr.W. Oct 29 '13 at 17:24
  • @B.Mr.W. you find explanation here: http://docs.python.org/2/library/functions.html#filter – Kent Oct 29 '13 at 21:32
1

If you want a simple list comprehension:

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

Output:

['C3S3', 'D4D4']
beroe
  • 11,784
  • 5
  • 34
  • 79