Regular Expressions: Search in list Ask Question

Regular Expressions: Search in list Ask Question

I want to filter strings in a list based on a regular expression.

Is there something better than [x for x in list if r.match(x)] ?

ベストアンサー1

Full Example (Python 3):
For Python 2.x look into Note below

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note below
print(newlist)

Prints:

['cat', 'wildcat', 'thundercat']

Note:

For Python 2.x developers, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).

Python 3 code example
Python 2.x code example

おすすめ記事