TokenQueue { public String chompBalanced(char open, char close) { int start = -1; int end = -1; int depth = 0; char last = 0; boolean inQuote = false; do { if (isEmpty()) { break; } Character c = consume(); if (last == 0 || last != ESC) { if ((c.equals('\'') || c.equals('"')) && c != open) { inQuote = !inQuote; } if (inQuote) { continue; } if (c.equals(open)) { depth++; if (start == -1) { start = pos; } } else if (c.equals(close)) { depth--; } } if (depth > 0 && last != 0) { end = pos; } last = c; } while (depth > 0); final String out = end >= 0 ? queue.substring(start, end) : ""; Validate.isTrue(depth == 0, "Did not find balanced maker at " + out); return out; } TokenQueue(String data); boolean isEmpty(); boolean matches(String seq); boolean matchesAny(String... seq); boolean matchesAny(char... seq); boolean matchChomp(String seq); boolean matchesWhitespace(); boolean matchesWord(); char consume(); void consume(String seq); String consumeTo(String seq); String consumeToAny(String... seq); String chompTo(String seq); String chompBalanced(char open, char close); static String unescape(String in); boolean consumeWhitespace(); String consumeNodeSelector(); String consumeIdentifier(); String remainder(); @Override String toString();  }
@Test public void chompBalanced() { TokenQueue tq = new TokenQueue(":contains(one (two) three) four"); String pre = tq.consumeTo("("); String guts = tq.chompBalanced('(', ')'); String remainder = tq.remainder(); assertEquals(":contains", pre); assertEquals("one (two) three", guts); assertEquals(" four", remainder); }