re.sub: non-greedy doesn't work as expected
<p>I have the following code in ipython. I expect it to remove the beginning "ab" since .*? is a non-greedy one. But why it remove all the way up to the last b?</p>

<pre><code>  In [15]: b="abcabcabc"

  In [16]: re.sub(".*?b","",b)
  Out[16]: 'c'
</code></pre>

<p>That is because, by default, <code>re.sub()</code> will search and replace all occurrences </p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; b="abcabcabc"
&gt;&gt;&gt; re.sub(".*?b","",b)
'c'
&gt;&gt;&gt; re.sub("^.*?b","",b)
'cabcabc'
&gt;&gt;&gt; re.sub(".*?b","",b, count=1)
'cabcabc'
&gt;&gt;&gt; re.sub(".*?b","",b, count=2)
'cabc'
</code></pre>

<p><br>
From <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">doc</a></p>

<pre><code>re.sub(pattern, repl, string, count=0, flags=0)
</code></pre>

python regex