Replace all occurrences of 'pattern' in part of a string using Python regex
<p>I would like to replace all '&lt;' symbols that are in between apple and orange with '-'.  </p>

<pre><code>&gt;&gt;&gt; print re.sub(r'(apple.*)&lt;(.*orange)', r'\1-\2', r'apple &lt; &lt; orange')
</code></pre>

<blockquote>
  <p>apple &lt; - orange</p>
</blockquote>

<pre><code>&gt;&gt;&gt; print re.sub(r'(apple.*)&lt;(?=.*orange)', r'\g&lt;1&gt;-', r'apple &lt; &lt; orange')
</code></pre>

<blockquote>
  <p>apple &lt; - orange</p>
</blockquote>

<p>One invocation to <code>re.sub</code> only processes non-overlapping matches.</p>

<p>One way around that is brute force:</p>

<pre><code>&gt;&gt;&gt; s = 'apple &lt; &lt; orange'
&gt;&gt;&gt; old = None
&gt;&gt;&gt; while s != old:
...    old = s
...    s = re.sub(r'(apple.*)&lt;(.*orange)', r'\1-\2', s)
... 
&gt;&gt;&gt; print s
apple - - orange
</code></pre>

python regex