Python Regular Expression; replacing a portion of match
<p>How would I limit match/replacement the leading zeros in e004_n07?  However, if either term contains all zeros, then I need to retain one zero in the term (see example below). For the input string, there will always be 3 digits in the first value and 2 digits in the second value.</p>

<p>Example input and output</p>

<pre><code>e004_n07 #e4_n7
e020_n50 #e20_n50
e000_n00 #e0_n0
</code></pre>

<p>Can this be accomplished with re.sub alone, or do I need to use re.search/re.match?</p>

<p>If you want to only remove zeros after letters, you may use:</p>

<pre><code>([a-zA-Z])0+
</code></pre>

<p>Replace with <code>\1</code> backreference. See the <a href="https://regex101.com/r/oI2vF0/1" rel="nofollow">regex demo</a>.</p>

<p>The <code>([a-zA-Z])</code> will capture a letter and <code>0+</code> will match 1 or more zeros. </p>

<p><a href="http://ideone.com/n1BaaV" rel="nofollow">Python demo</a>:</p>

<pre><code>import re
s = 'e004_n07'
res = re.sub(r'([a-zA-Z])0+', r'\1', s)
print(res)
</code></pre>

<p>Note that <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><strong><code>re.sub</code></strong></a> will find and replace all non-overlapping matches (will perform a global search and replace). If there is no match, the string will be returned as is, without modifications. So, there is no need using additional <code>re.match</code>/<code>re.search</code>.</p>

<p><strong>UDPATE</strong></p>

<p>To keep 1 zero if the numbers only contain zeros, you may use</p>

<pre><code>import re
s = ['e004_n07','e000_n00']
res = [re.sub(r'(?&lt;=[a-zA-Z])0+(\d*)', lambda m: m.group(1) if m.group(1) else '0', x) for x in s]
print(res)
</code></pre>

<p>See the <a href="http://ideone.com/QeFcsL" rel="nofollow">Python demo</a></p>

<p>Here, <code>r'(?&lt;=[a-zA-Z])0+(\d*)'</code> regex matches one or more zeros (<code>0+</code>) that are after an ASCII letter (<code>(?&lt;=[a-zA-Z])</code>) and then any other digits (0 or more) are captured into Group 1 with <code>(\d*)</code>. Then, in the replacement, we check if Group 1 is empty, and if it is empty, we insert <code>0</code> (there are only zeros), else, we insert Group 1 contents (the remaining digits after the first leading zeros).</p>

python regex