JAVA去除括号及里面的内容(正则表达式 && 代码算法)

1.正则表达式:
中文【】及{}要用\\转义

public final static String REGEX_ALL_BRACKETS = "\\<.*?\\>|\\(.*?\\)|\\(.*?\\)|\\[.*?\\]|\\【.*?\\】|\\{.*?\\}";

String regexString = context.replaceAll(REGEX_ALL_BRACKETS, "");

2.代码算法实现
转载:https://www.cnblogs.com/diehuacanmeng/p/13223334.html

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;
    }

你可能感兴趣的:(java,java)