Regex python findall issue
<p>From the test string:</p>

<pre><code> test=text-AB123-12a
 test=text-AB123a
</code></pre>

<p>I have to extract only <code>'AB123-12'</code> and <code>'AB123'</code>, but:</p>

<pre><code> re.findall("[A-Z]{0,9}\d{0,5}(?:-\d{0,2}a)?", test)
</code></pre>

<p>returns:</p>

<pre><code>['', '', '', '', '', '', '', 'AB123-12a', '']
</code></pre>

<p>What are all these extra empty spaces? How do I remove them?</p>

<p>Since letters or digits are optional at the beginning, you must ensure that there's at least one letter or one digit, otherwise your pattern will match the empty string at each position in the string. You can do it starting your pattern with a lookahead. Example:</p>

<pre><code>re.findall(r'(?=[A-Z0-9])[A-Z]{0,9}\d{0,5}(?:-\d\d?)?(?=a)', test)
</code></pre>

<p>In this way the match can start with a letter or with a digit.</p>

<p>I assume that when there's an hyphen, it is followed by at least one digit (otherwise what is the reason of this hyphen?). In other words, I assume that <code>-a</code> isn't possible at the end. (correct me if I'm wrong.)</p>

<p>To exclude the "a" from the match result, I putted it in a lookahead.</p>

python regex