Using Python's regex .match() method to get the string before and after an underscore
<p><strong><em>I have the following code...</em></strong></p>

<pre><code>tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]

for table in tablesInDataset:
    tableregex = re.compile("\d{8}")
    tablespec = re.match(tableregex, table)

    everythingbeforedigits = tablespec.group(0)
    digits = tablespec.group(1)
</code></pre>

<p>My regex should only return the string if it contains 8 digits after an underscore. Once it returns the string, I want to use <code>.match()</code> to get two groups using the <code>.group()</code> method. The first group should contain a string will all of the characters before the digits and the second should contain a string with the 8 digits. </p>

<p>Could someone please help me figure out the correct regex to use to get the results I am looking for using <code>.match()</code> and <code>.group()</code>?</p>

<p>Use capture groups:</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; pat = re.compile(r'(?P&lt;name&gt;.*)_(?P&lt;number&gt;\d{8})')
&gt;&gt;&gt; pat.findall(s)
[('henry_jones', '12345678')]
</code></pre>

<p>You get the nice feature of named groups, if you want it:</p>

<pre><code>&gt;&gt;&gt; match = pat.match(s)
&gt;&gt;&gt; match.groupdict()
{'name': 'henry_jones', 'number': '12345678'}
</code></pre>

python regex string iterator