Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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’>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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’

>Solution :

Try:

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading