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