python: regex - catch variable number of groups
<p>I have a string that looks like:</p>

<pre><code>TABLE_ENTRY.0[hex_number]= &lt;FIELD_1=hex_number, FIELD_2=hex_number..FIELD_X=hex&gt;
TABLE_ENTRY.1[hex_number]= &lt;FIELD_1=hex_number, FIELD_2=hex_number..FIELD_Y=hex&gt;
</code></pre>

<p>number of fields is unknown and varies from entry to entry, I want to capture
each entry separately with all of its fields and their values.</p>

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

<pre><code>([A-Z_0-9\.]+\[0x[0-9]+\]=)(0x[0-9]+|0):\s+&lt;(([A-Z_0-9]+)=(0x[0-9]+|0))
</code></pre>

<p>which matches the table entry and the first field, but I dont know how to account for variable number of fields.</p>

<p>for input:</p>

<pre><code>ENTRY_0[0x130]=0: &lt;FIELD_0=0, FIELD_1=0x140... FIELD_2=0xff3&gt;
</code></pre>

<p>output should be:</p>

<pre><code>ENTRY 0:
        FIELD_0=0
        FIELD_1=0x140
        FIELD_2=ff3
ENTRY 1:
        ...
</code></pre>

<p>In short, it's impossible to do all of this in the <code>re</code> engine. You cannot generate more groups dynamically. It will all put it in one group. You should re-parse the results like so:</p>

<pre><code>import re
input_str = ("TABLE_ENTRY.0[0x1234]= &lt;FIELD_1=0x1234, FIELD_2=0x1234, FIELD_3=0x1234&gt;\n"
             "TABLE_ENTRY.1[0x1235]= &lt;FIELD_1=0x1235, FIELD_2=0x1235, FIELD_3=0x1235&gt;")
results = {}
for match in re.finditer(r"([A-Z_0-9\.]+\[0x[0-9A-F]+\])=\s+&lt;([^&gt;]*)&gt;", input_str):
    fields = match.group(2).split(", ")
    results[match.group(1)] = dict(f.split("=") for f in fields)

&gt;&gt;&gt; results
{'TABLE_ENTRY.0[0x1234]': {'FIELD_2': '0x1234', 'FIELD_1': '0x1234', 'FIELD_3': '0x1234'}, 'TABLE_ENTRY.1[0x1235]': {'FIELD_2': '0x1235', 'FIELD_1': '0x1235', 'FIELD_3': '0x1235'}}
</code></pre>

<p>The output will just be a large dict consisting of a table entry, to a dict of it's fields.</p>

<p>It's also rather convinient as you may do this:</p>

<pre><code>&gt;&gt;&gt; results["TABLE_ENTRY.0[0x1234]"]["FIELD_2"]
'0x1234'
</code></pre>

<p>I personally suggest stripping off "TABLE_ENTRY" as it's repetative but as you wish.</p>

python regex