简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM