B.Mr.W.
B.Mr.W.

Reputation: 19628

Search List using Regular Expression

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.

Upvotes: 0

Views: 272

Answers (2)

beroe
beroe

Reputation: 12316

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

Upvotes: 1

Kent
Kent

Reputation: 195049

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

Upvotes: 2

Related Questions