Instead of word boundaries, you can also match the character before and after the word using the pattern (\s|^) and (\s|$) .
Breakdown : \s corresponds to each space character, which seems to be what you are trying to achieve as you exclude dashes. ^ and $ ensure that if a word is either the first or the last in a line (i.e., No character before or after), they also match.
Your code will look something like this:
pattern = re.compile(r'(\s|^)(word)(\s|$)') result = pattern.sub(r"\1match\3", "-word- word")
Since this solution uses character classes such as \s , this means that they can be easily replaced or extended. For example, if you want your words to be separated by spaces or commas, your template will look something like this: r'(,|\s|^)(word)(,|\s|$)' .
source share