I have a simple function to remove a "word" from some text:
def remove_word_from(word, text):
if not text or not word: return text
rec = re.compile(r'(^|\s)(' + word + ')($|\s)', re.IGNORECASE)
return rec.sub(r'\1\3', text, 1)
The problem, of course, is that if word contains characters such as "(" or ")" things break, and it generally seems unsafe to stick a random word in the middle of a regex.
What's best practice for handling cases like this? Is there a convenient, secure function I can call to escape "word" so it's safe to use?
You can use re.escape(word)
to escape the word.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With