title: Java Splitting a String by parentheses
body: <p>If I had an equation like this:</p>
  <pre><code>(equ1)+(equ2)-sqrt(equ2)
  </code></pre>
  <p>How do I collect the top most parentheses only? The equations can have things like:</p>
  <pre><code>((inner equation))+((inner equation))
  </code></pre>
  <p>So splitting by a regex such as:</p>
  <pre><code>.split(&quot;[()]&quot;)
  </code></pre>
  <p>Doesn't help me</p>
  <p>I have tried to create a for loop:</p>
  <pre><code>for(int i = 0; i &lt; equation.size(); i++) {
          str = equation.get(i).toString();
          str2 = string;
          elements = str2.split(&quot;(\((?:[^()]|(?1))*\))&quot;);
          
          System.out.println(Arrays.toString(parSolver.toArray()));
      }
  </code></pre>
  <p>to replace <code>((inner equation)) + ((inner equation))</code> with <code>&quot;Number1&quot;+&quot;Number2&quot;</code> but i cannot do that without separating the parentheses first; any help is appreciated.</p>
  <p>I have to note that the equation is already answered, I just need to plug it into the string by replacing the parentheses with the answer:</p>
  <pre><code>equation element 1: &quot;&quot;Answer&quot;
  str: ((inner equation))+ ((inner equation))
  becomes: &quot;Answer&quot;+((inner equation))
  (Repeat process)
  </code></pre>
  <p>One thing i also tried was trying to get the parentheses locations:</p>
  <pre><code>0,6 8,13
  </code></pre>
  <p>And i tried to set a substring to that value between 0,6 and 8,13. and replace it:</p>
  <pre><code>str = string.substring(0, 6);
  string = string.replace(str, &quot;Answer&quot;);
  </code></pre>
  <p>But something is severely wrong with the values because i did count where each parentheses is, like if '(' is at index 0 and ')' is at index 6, then why doesn't this sub-string cooperate and give me the value: <code>(_____)</code>?</p>
  <p>The errors I encounter with that strategy are <code>Index out of bounds</code> and I can never seem to collect the right sub-string sections. Its always over the string length, even though the parentheses locations are IN the string. The iteration in the sub-string definitely doesn't start at 0 or I wouldn't have this problem.</p>
  <p>Note: What if i could define the parentheses? like i have 2 sets, three sets, etc. Will I be able to use a regex?</p>