Match a substring in Pandas wit str.extract method
<p>I have a string looking like:</p>

<pre><code>29818-218705-61709-2    
</code></pre>

<p>I want to extract the second to last 5 digits number between the two dashes</p>

<pre><code>61709
</code></pre>

<p>each string is contained in a pandas series:</p>

<p>I came up with:</p>

<pre><code>df.id.str.extract(r'[.-]([0-9]{5})[.-]?')
</code></pre>

<p>but it extracts the first 5 digits group.</p>

<p>I can I match the one I want?</p>

<p>You may use</p>

<pre><code>[.-]([0-9]{5})[.-][0-9]+$
</code></pre>

<p>See <a href="https://regex101.com/r/UHzTOq/1" rel="nofollow">this regex demo</a></p>

<p><strong>Details</strong>:</p>

<ul>
<li><code>[.-]</code> - a <code>.</code> or <code>-</code> separator</li>
<li><code>([0-9]{5})</code> - Group 1 capturing 5 digits</li>
<li><code>[.-]</code> - again a separator</li>
<li><code>[0-9]+</code> -1+ digits</li>
<li><code>$</code> - end of string.</li>
</ul>

<p>Thanks to the <code>$</code> anchor, the digit groups that are at the end are matched.</p>

<p>An alternative is to leverage backtracking with:</p>

<pre><code>^.*[.-]([0-9]{5})[.-]
</code></pre>

<p>See <a href="https://regex101.com/r/UHzTOq/3" rel="nofollow">this demo</a></p>

<p>The <code>^.*</code> will match any 0+ chars other than linebreak symbols from the start of the string, as many as possible, so the last <code>-|.</code>+<code>5 digits</code>+<code>-|.</code> are matched.</p>

python regex string pandas