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

Time:10-10

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'

CodePudding user response:

Try:

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

>>> p.search(sentence)
<re.Match object; span=(13, 22), match='abandoned'>
  • Related