tgr
tgr

Reputation: 3608

Query a set with an regex

I have a set of strings and I want to ask it for all contained elements, that match a specific RegEx. For example:

set = set(['abcd', 'abdd', 'acdd'])
set.findAll('ab.d')

This should return:

['abcd', 'abdd']

Is there a way to do so?

Upvotes: 2

Views: 66

Answers (3)

Bhargav Rao
Bhargav Rao

Reputation: 52151

This can be accomplished using map and filter as in

>>> s = {'abcd', 'abdd', 'acdd'}
>>> pat = re.compile('ab.d')
>>> map(lambda x:x.string,filter(None, map(pat.search,s)))
['abcd', 'abdd']

Note that map is microscopically faster than a list comprehension.

bhargav@bhargav:~$ python -m timeit "import re;s = {'abcd', 'abdd', 'acdd'};[el for el in s if re.search('ab.d', el)]"
100000 loops, best of 3: 4.59 usec per loop
bhargav@bhargav:~$ python -m timeit "import re;s = {'abcd', 'abdd', 'acdd'};pat = re.compile('ab.d'); map(lambda x:x.string,filter(None, map(pat.search,s)))"
100000 loops, best of 3: 4.21 usec per loop

As you can see, using map and filter makes it 0.38 microseconds faster.

However if you consider readability orlp's list comprehension is better. (In that case, this is an alternative way)

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107337

You can use re.search within a list comprehension :

>>> s=set(['abcd', 'abdd', 'acdd'])
>>> [i for i in s if re.search(r'ab.d',i)]
['abcd', 'abdd']

Upvotes: 3

orlp
orlp

Reputation: 117771

Loop over all elements in the set, and filter on the regex:

>>> s = {'abcd', 'abdd', 'acdd'}
>>> r = [el for el in s if re.search('ab.d', el)]
>>> r
['abcd', 'abdd']

Upvotes: 3

Related Questions