title: Parsing Nested Bracket String in java
body: <p>I want to parse strings with (nested) brackets and values like:</p>
  
  <pre><code>A,(B,C),(D,(B,D),X)
  </code></pre>
  
  <p>I want the inner tuples as f.ex ArrayList, like ArrayList(B,C) or ArrayList(D,ArrayList(B,D)).</p>
  
  <p>My first idea was to use a Stack, but i have problems when i have a tuple in a tuple and then after the inner tuple comes another value, like (Z,(A,B),C).</p>
  
  <pre><code>public static ArrayList&lt;Object&gt; parse(String str, ArrayList&lt;Object&gt; result) {
      ArrayList&lt;Object&gt; tmp = result;
      if (str.length() == 0) {
          return tmp;
      } else if (str.charAt(0) == '(') {
          ArrayList&lt;Object&gt; al = new ArrayList&lt;Object&gt;();
          tmp.add(al);
          str = str.substring(1, str.length());
          return parse(str, tmp);
      }else if(str.charAt(0) == ',')
      {
          str = str.substring(1,str.length());
          return parse(str,tmp);
      }
      else {
          ArrayList&lt;String&gt; al = new ArrayList&lt;String&gt;();
          al.add(""+str.charAt(0));
          tmp.add(al);
  
          str = str.substring(1, str.length());
          return parse(str,tmp);
      }
  }
  
  public static void main(String[] args) {
      ArrayList&lt;Object&gt; al = new ArrayList&lt;Object&gt;();
      System.out.println(parse("A,(B),(C,(D,E),F)",al));  
  }
  </code></pre>
  
  <p>Output:</p>
  
  <blockquote>
    <p>[[A], [], [B], [)], [], [C], [], [D], [E], [)], [F], [)]]</p>
  </blockquote>