question: public String chompBalanced ( char open , char close ) { StringBuilder accum = new StringBuilder ( ) ; int depth = 0 ; char last = 0 ; do { if ( isEmpty ( ) ) break ; Character c = consume ( ) ; if ( last == 0 || last != ESC ) { if ( c . equals ( open ) ) depth ++ ; else if ( c . equals ( close ) ) depth -- ; } if ( depth > 0 && last != 0 ) accum . append ( c ) ; last = c ; } while ( depth > 0 ) ; return accum . toString ( ) ; }
target:  Pulls a balanced string off the queue. E.g. if queue is "(one (two) three) four", (,) will return "one (two) three", and leave " four" on the queue. Unbalanced openers and closers can be escaped (with \). Those escapes will be left in the returned string, which is suitable for regexes (where we need to preserve the escape), but unsuitable for contains text strings; use unescape for that.