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

I want to find if a string matches this rule using a regex:

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 in regex is that I have hundreds of rules like her and different from her, so I want to save them as templates in a dict.

The only thing I could think of is this, but it doesn't look pretty:

re.search(r'foo.*(a|boo|blah)|(a|boo|blah).*foo')
+4
source share
1 answer

You can join array elements with |to create a regular expression regular expression:

>>> 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']

, ^(?=.*\b(?:a|boo|blah)\b).*foo, list_of_words foo .

+5

All Articles