PratPor PratPor - 1 year ago 112
Python Question

Regex - replace word having plus or brackets

In Python, I am trying to do

text = re.sub(r'\b%s\b' % word, "replace_text", text)

to replace a word with some text. Using
rather than just doing
to replace only if the whole word matches using
. Problem comes when there are characters like
+, (, [ etc
in word. For example

Regex treats this
as wildcard for one or more and breaks with error.
sre_constants.error: nothing to repeat
. Same is in the case of

Could find a fix for this after searching around a bit. Is there a way?

Answer Source

Just use re.escape(string):

word = re.escape(word)
text = re.sub(r'\b{}\b'.format(word), "replace_text", text)

It replaces all critical characters with a special meaning in regex patterns with their escape forms (e.g. \+ instead of +).

Just a sidenote: formatting with the percent (%) character is deprecated and was replaced by the .format() method of strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download