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><code>\b</code> basically denotes a word boundary on characters other than <code>[a-zA-Z0-9_]</code> which includes spaces as well. Surround <code>word</code> with negative lookarounds to ensure there is no non-space character after and before it:</p>

<pre><code>re.compile(r'(?&lt;!\S)word(?!\S)')
</code></pre>

python regex