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>

<p>You can replace it directly:</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; s = 'sdfjoiweng%@$foo$fsoifjoi'
&gt;&gt;&gt; print re.sub('foo','bar',s)
sdfjoiweng%@$bar$fsoifjoi
</code></pre>

<p>It will also work for more occurrences of <code>foo</code> like below:</p>

<pre><code>&gt;&gt;&gt; s = 'sdfjoiweng%@$foo$fsoifoojoi'
&gt;&gt;&gt; print re.sub('foo','bar',s)
sdfjoiweng%@$bar$fsoibarjoi
</code></pre>

<p>If you want to replace only the 1st occurrence of <code>foo</code> and not all the <code>foo</code> occurrences in the string then alecxe's answer does exactly that.</p>

python regex