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><em><strong>edit:</strong> Don't let anybody talk you out of validating the format of the fixed data. If that's what you need, don't settle for something overly simple .</em>  </p>

<p>Not very pretty, but in a situation that seems fixed, you can just<br>
set all the permutations, then blindly capture the good parts,<br>
leave out the zero's then substitute it all back.  </p>

<p>Find <code>([a-z])(?:([1-9][0-9][0-9])|0([1-9][0-9])|00([1-9]))(_[a-z])(?:([1-9][0-9])|0([1-9]))</code></p>

<p>Replace <code>$1$2$3$4$5$6$7</code>  </p>

<p>Expanded  </p>

<pre><code> ( [a-z] )                     # (1)
 (?:
      ( [1-9] [0-9] [0-9] )         # (2)
   |  
      0
      ( [1-9] [0-9] )               # (3)
   |  
      00
      ( [1-9] )                     # (4)
 )
 ( _ [a-z] )                   # (5)
 (?:
      ( [1-9] [0-9] )               # (6)
   |  
      0
      ( [1-9] )                     # (7)
 )
</code></pre>

<p>Output  </p>

<pre><code> **  Grp 0 -  ( pos 0 , len 8 ) 
e004_n07  
 **  Grp 1 -  ( pos 0 , len 1 ) 
e  
 **  Grp 2 -  NULL 
 **  Grp 3 -  NULL 
 **  Grp 4 -  ( pos 3 , len 1 ) 
4  
 **  Grp 5 -  ( pos 4 , len 2 ) 
_n  
 **  Grp 6 -  NULL 
 **  Grp 7 -  ( pos 7 , len 1 ) 
7  
</code></pre>

python regex