Mo.
Mo.

Reputation: 42523

Python re: if string has one word AND any one of a list of words?

I want to find if a string matches on this rule using a regular expression:

list_of_words = ['a', 'boo', 'blah']
if 'foo' in temp_string and any(word in temp_string for word in list_of_words)

The reason I want it in a regular expression is that I have hundreds of rules like it and different from it so I want to save them all as patterns in a dict.

The only one I could think of is this but it doesn't seem pretty:

re.search(r'foo.*(a|boo|blah)|(a|boo|blah).*foo')

Upvotes: 4

Views: 995

Answers (1)

anubhava
anubhava

Reputation: 785196

You can join the array elements using | to construct a lookahead assertion regex:

>>> list_of_words = ['a', 'boo', 'blah']

>>> reg = re.compile( r'^(?=.*\b(?:' + "|".join(list_of_words) + r')\b).*foo' )

>>> print reg.pattern
^(?=.*\b(?:a|boo|blah)\b).*foo

>>> reg.findall(r'abcd foo blah')
['abcd foo']

As you can see we have constructed a regex ^(?=.*\b(?:a|boo|blah)\b).*foo which asserts presence of one word from list_of_words and matches foo anywhere.

Upvotes: 6

Related Questions