Match path but not os.path
<p>I want to match the string <code>path</code> but not the string <code>os.path</code>. How do I go about that ? Tried <a href="http://stackoverflow.com/questions/2953039/regular-expression-for-a-string-containing-one-word-but-not-another"><code>(?!(os\.path))\bpath\b</code></a> but I still get all <code>os.path</code>S</p>

<p>You can use a look-behind based regex, like</p>

<pre><code>(?&lt;!os\.)\bpath\b
</code></pre>

<p>This basically matches the exact word <code>path</code> and ensures that it is not preceded by <code>os.</code> If you want to avoid similar constructs, like <code>sys.path</code> or <code>xx.path</code> you could use <code>(?&lt;!\w\.)</code> as look-behind instead.</p>

<p>See the <a href="https://regex101.com/r/vkvKO2/1" rel="nofollow">regex101 demo</a>.</p>

python regex python-2.7