find if a word from a list of words exist in a string using regex

Question:

I have a list of words

words = ['abandon', 'abandonments', 'abandons', 'abandonment', 'abandon', 'abandoned', 'abandons', 'abandoning']

I want to know if any of those words are in the following sentence

sentence = "The children abandoned themselves to the delights of the warm summer day."

desired output <re.Match object; span=(13, 21), match=’abandoned’>

I want to do it with regex re.search (only the 1st match is required here) and get the matched string and its span.

Please note that I’m looking for words here not just strings, so the desired output should be ‘abandoned’ not ‘abandon’

Asked By: ZZZ

||

Answers:

Try:

p = re.compile(fr"b({'|'.join(words)})b")

>>> p.search(sentence)
<re.Match object; span=(13, 22), match='abandoned'>
Answered By: Pierre D
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.