title: Java regex ability to handle nested matches separately
body: <p>I completely can't figure out how to write pattern, to achieve nested fractions in latex with my regex.</p>
  
  <p>Here is couple sample user inputs:</p>
  
  <pre><code>"fractionx+3over5moveout+2"
  "fractionfractionx+1over7moveoutover3moveout+1", 
  "fractionfractionfractionx+3over3moveoutoverx+2moveoutover7moveout+1".
  </code></pre>
  
  <p>Here's my regex code(I made partial versions):</p>
  
  <pre><code>\\Final version with closing "moveout" phrase
  regexPattern = Pattern.compile(fraction(?&lt;upper&gt;.*?)over(?&lt;lower&gt;.*?)moveout);
  regexMatcher = regexPattern.matcher(userInput);
  mathFormulaInLaTeX = regexMatcher.replaceAll(\\frac{${upper}} {${lower}});
  
  \\Starting version without "over" keyword
  regexPattern = Pattern.compile(fraction(?&lt;upper&gt;.*));
  regexMatcher = regexPattern.matcher(userInput);
  mathFormulaInLaTeX = regexMatcher.replaceAll(\\frac{${upper}} {});
  </code></pre>
  
  <p>With the following inputs I get results:</p>
  
  <p>Input: "fractionx+3over5moveout+2"</p>
  
  <p>(The final regex version works fine with only one fraction)
  <a href="https://i.stack.imgur.com/ZVJxB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZVJxB.png" alt="enter image description here"></a></p>
  
  <p>Input: "fractionfractionx+1"</p>
  
  <p>(Starting version without "over" keyword with nested fractions not working properly)
  <a href="https://i.stack.imgur.com/LnqHK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LnqHK.png" alt="enter image description here"></a></p>
  
  <p>Input: "fractionfractionx+1over7moveoutover3moveout+1"</p>
  
  <p>(The final regex version with nested fractions adds moveout word)
  <a href="https://i.stack.imgur.com/zSMny.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zSMny.png" alt="enter image description here"></a></p>
  
  <p>Input: "fractionfractionfractionx+3over3moveoutoverx+2moveoutover7moveout+1"</p>
  
  <p>(Completly misclassified)</p>
  
  <p><a href="https://i.stack.imgur.com/lQjlK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lQjlK.png" alt="enter image description here"></a></p>
  
  <p>Is there a neat pattern solution for any number of nested fractions, to get rid of "moveout" word displaying and make nested fraction like this:</p>
  
  <p><a href="https://i.stack.imgur.com/R860Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R860Z.png" alt="enter image description here"></a></p>
  
  <p>I appreciate any help.</p>