Predictive Hacks

How to use a list of strings in regex

This is how you can use a list of strings in regex functions like the sub, find-all, etc. It also adds word boundaries so it will not match parts of other strings(e.g. Nick in Nicky).

import re

compiled_list=re.compile("|".join(["\\b"+i+"\\b" for i in names]))

test_string='Names: Billy, George, Nick, Nicky'
re.sub(compiled_list, '',test_string)
'Names: , , , Nicky'

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s