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>What you need is a negative lookbehind.</p>

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

<p>To cite the <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">documentation</a>:</p>

<blockquote>
  <p><code>(?&lt;!...)</code>
      Matches if the current position in the string is not preceded by a match for ....</p>
</blockquote>

<p>So this will only match, if the word-break <code>\b</code> is not preceded with a minus sign <code>-</code>.</p>

<p>If you need this for the end of the string you'll have to use a negative lookahead which will look like this: <code>(?!-)</code>. The complete regular expression will then result in: <code>(?&lt;!-)\bword(?!-)\b</code> </p>

python regex