question: @ CheckReturnValue @ CheckForNull static public String parenQuote ( @ CheckForNull String in ) { if ( in == null || in . equals ( "" ) ) { return in ; } StringBuilder result = new StringBuilder ( ) ; int level = 0 ; for ( int i = 0 ; i < in . length ( ) ; i ++ ) { char c = in . charAt ( i ) ; switch ( c ) { case '(' : level ++ ; break ; case '\\' : result . append ( '\\' ) ; break ; case ')' : level -- ; if ( level < 0 ) { level = 0 ; result . append ( '\\' ) ; } break ; default : break ; } result . append ( c ) ; } return new String ( result ) ; }
target:  Quotes unmatched closed parentheses; matched ( ) pairs are left unchanged. If there's an unmatched ), quote it with \, and quote \ with \ too.