I simplified my code to the specific problem I am having.
import re pattern = re.compile(r\'\\bword\\b\') result = pattern.sub(lambda x: \"match\", \"-word-
\b basically denotes a word boundary on characters other than [a-zA-Z0-9_] which includes spaces as well. Surround word with negative lookarounds to ensure there is no non-space character after and before it:
\b
[a-zA-Z0-9_]
word
re.compile(r'(?