How to make word boundary \b not match on dashes
<p>I simplified my code to the specific problem I am having.</p>

<pre><code>import re
pattern = re.compile(r'\bword\b')
result = pattern.sub(lambda x: "match", "-word- word")
</code></pre>

<p>I am getting</p>

<pre><code>'-match- match'
</code></pre>

<p>but I want </p>

<pre><code>'-word- match'
</code></pre>

<p>edit:  </p>

<p>Or for the string <code>"word -word-"</code></p>

<p>I want</p>

<pre><code>"match -word-"
</code></pre>

<p>Instead of word boundaries, you could also match the character before and after the word with a <code>(\s|^)</code> and <code>(\s|$)</code> pattern. </p>

<p><strong>Breakdown</strong>: <code>\s</code> matches every whitespace character, which seems to be what you are trying to achieve, as you are excluding the dashes. The <code>^</code> and <code>$</code> ensure that if the word is either the first or last in the string(ie. no character before or after) those are matched too.</p>

<p>Your code would become something like this:</p>

<pre><code>pattern = re.compile(r'(\s|^)(word)(\s|$)')
result = pattern.sub(r"\1match\3", "-word- word")
</code></pre>

<p>Because this solution uses character classes such as <code>\s</code>, it means that those could be easily replaced or extended. For example if  you wanted your words to be delimited by spaces or commas, your pattern would become something like this: <code>r'(,|\s|^)(word)(,|\s|$)'</code>.</p>

python regex