Python regex, how to replace multiple groups from multiple matches
<p>I have a hunch I'm not seeing the simple solution to this so before I tear my hair out, maybe some one can help.</p>

<p>This is a bit of code:</p>

<pre><code>gr = regex.compile(r'({[^{]*(?&gt;{[^{}]+})*)\s\\over\s([^{}]+(?&gt;{[^{}]*})*})')
string1 = "{a \over b}"
string2 = "{x \over b{x}} {{d}d \over x}}"

m = regex.match(gr,string2)

reLine = regex.sub(gr,r"\\test"+m.group(1)+"}{"+m.group(2),string2)
</code></pre>

<p>The objective is basically this:</p>

<pre><code>before {a \over b}
after \test{a}{b}
</code></pre>

<p>And I have to look through the text file and replace all these matches.</p>

<p>My problem is with regex.search or regex.match it only matches once and returns one match with its groups, but I need multiple matches in case {a \over b} repeats multiple times on the same line.</p>

<p>So with 'string2' it captures '{x' as the first group, 'b{x}}' as the second, and stops capturing. So then when I try to replace, it replaces the groups of the first match with the second '\over' equation as well.</p>

<p>I have practiced regular expressions on regexr.com and it has a 'replace' function. It takes all the matches and replaces ($1,$2) all the matches and groups respectively.</p>

<p>Am I missing something on python regex module? Or is this problem more complicated than I imagined?</p>

<p>Thanks. </p>

<p>To anyone interested:
After some thought I solved my own problem by using regex.split.</p>

<p>I split the whole line by catching wider matches, and then replacing each match individually.</p>

python