private static StringPointer matchBalance ( MatchState ms, StringPointer ss, StringPointer p ) {

        BaseLib.luaAssert(!(p.getChar () == 0 || p.getChar ( 1 ) == 0), "unbalanced pattern");

        StringPointer s = ss.getClone();
        if ( s.getChar () != p.getChar () ) {
            return null;
        } else {
            int b = p.getChar ();
            int e = p.getChar ( 1 );
            int cont = 1;

            while ( s.preIncrStringI ( 1 ) < ms.endIndex ) {
                if ( s.getChar () == e ) {
                    if (  -- cont == 0 ) {
                        StringPointer sp = s.getClone();
                        sp.postIncrString ( 1 );
                        return sp;
                    }
                } else if ( s.getChar () == b ) {
                    cont ++;
                }
            }
        }
        return null;  /* string ends out of balance */
    }
Only works with non-negative numbers
main/src/main/java/cgeo/geocaching/wherigo/kahlua/stdlib/StringLib.java