Regular Expressions: Search in list

Viewed 314223

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

3 Answers

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

Related