GreenAsJade
GreenAsJade

Reputation: 14685

Check if a list has one or more strings that match a regex

If need to say

if <this list has a string in it that matches this rexeg>:
    do_stuff()

I found this powerful construct to extract matching strings from a list:

[m.group(1) for l in my_list for m in [my_regex.search(l)] if m]

...but this is hard to read and overkill. I don't want the list, I just want to know if such a list would have anything in it.

Is there a simpler-reading way to get that answer?

Upvotes: 9

Views: 153

Answers (1)

timgeb
timgeb

Reputation: 78690

You can simply use any. Demo:

>>> lst = ['hello', '123', 'SO']
>>> any(re.search('\d', s) for s in lst)
True
>>> any(re.search('\d{4}', s) for s in lst)
False

use re.match if you want to enforce matching from the start of the string.

Explanation:

any will check if there is any truthy value in an iterable. In the first example, we pass the contents of the following list (in the form of a generator):

>>> [re.search('\d', s) for s in lst]
[None, <_sre.SRE_Match object at 0x7f15ef317d30>, None]

which has one match-object which is truthy, while None will always evaluate to False in a boolean context. This is why any will return False for the second example:

>>> [re.search('\d{4}', s) for s in lst]
[None, None, None]

Upvotes: 7

Related Questions