how to check if both query strings (with wildcards) are present using regex in python

Viewed 47

I have two query strings, both of which contains wildcards. We can check if any of the two query strings are present like below:

import re
def wildcards2regex (pattern):
    return ( pattern.replace('?', '[a-zA-Z]{1}').replace('*', '.*') )

string = 'christopher susan'
s1='chris*'
r1 = wildcards2regex(s1)
s2 = 'sus??'
r2 = wildcards2regex(s2)
q = r1+'|'+r2
bool(re.search(q, string))

Now I wonder what to do if I want to check if both query string are present? obviously replacing '|' with '&' does not work. Do anyone know how to achieve that?

2 Answers

You may consider this code:

>>> import re
>>> def wildcards2regex (pattern):
...    return ( pattern.replace('?', '[a-zA-Z]').replace('*', '.*') )
...
>>> string = 'christopher susan'
>>> s1='chris*'
>>> r1 = wildcards2regex(s1)
>>> s2 = 'sus??'
>>> r2 = wildcards2regex(s2)
>>> q = re.compile(r'(?=.*{})(?=.*{})'.format(r1, r2))
>>> bool(re.search(q, string))
True

Take note of this regex building:

q = re.compile(r'(?=.*{})(?=.*{})'.format(r1, r2))

Here we are building a regex with 2 conditions defined using positive lookahead assertions that asserts both of your query strings.

Related