How can I replace all occurrences of a substring using regex?
<p>I have a string, <code>s = 'sdfjoiweng%@$foo$fsoifjoi'</code>, and I would like to replace <code>'foo'</code> with <code>'bar'</code>. </p>

<p>I tried <code>re.sub(r'\bfoo\b', 'bar', s)</code> and <code>re.sub(r'[foo]', 'bar', s)</code>, but it doesn't do anything. What am I doing wrong?</p>

<blockquote>
  <p><code>re.sub(r'\bfoo\b', 'bar', s)</code></p>
</blockquote>

<p>Here, the <code>\b</code> defines <a href="http://www.regular-expressions.info/wordboundaries.html" rel="nofollow">the word boundaries</a> - positions between a word character (<code>\w</code>) and a non-word character - exactly what you have matching for <code>foo</code> inside the <code>sdfjoiweng%@$foo$fsoifjoi</code> string. Works for me:</p>

<pre><code>In [1]: import re

In [2]:  s = 'sdfjoiweng%@$foo$fsoifjoi'

In [3]: re.sub(r'\bfoo\b', 'bar', s)
Out[3]: 'sdfjoiweng%@$bar$fsoifjoi'
</code></pre>

python regex