JAVA去除括号及里面的内容

public class Test {

    public static void main(String[] args) {
        String str = "-210(10%)-210(10%)";
        str = clearBracket(str, '(', ')');
        System.out.println(str);
    }

    /**
     * 去除两符号间内容
     * @param context
     * @param left
     * @param right
     * @return
     */
    private static String clearBracket(String context, char left, char right) {
        int head = context.indexOf(left);
        if (head == -1) {
            return context;
        } else {
            int next = head + 1;
            int count = 1;
            do {
                if (context.charAt(next) == left) {
                    count++;
                } else if (context.charAt(next) == right) {
                    count--;
                }
                next++;
                if (count == 0) {
                    String temp = context.substring(head, next);
                    context = context.replace(temp, "");
                    head = context.indexOf(left);
                    next = head + 1;
                    count = 1;
                }
            } while (head != -1);
        }
        return context;
    }
}

 

posted @ 2020-07-02 10:33  蝶花残梦  阅读(2705)  评论(0编辑  收藏  举报
Live2D