java 去除括号里的内容

来源:互联网 发布:统计学博士 知乎 编辑:程序博客网 时间:2024/06/11 02:08
/**
 * Project Name:MonitoringPlatform-services
 * File Name:Test1.java
 * Package Name:com.monitoring.core
 * Date:2017年6月20日下午3:13:31
 * Copyright (c) 2017, chenzhou1025@126.com All Rights Reserved.
 *
 */

package com.monitoring.core;

/**
 * ClassName:Test1 <br/>
 * Function: ADD FUNCTION. <br/>
 * Reason: ADD REASON. <br/>
 * Date: 2017年6月20日 下午3:13:31 <br/>
 *
 * @author wpengfei
 * @version
 * @since JDK 1.6
 * @see
 */
public class Test1 {
    
    public static void main(String[] args) {
        
        String str = "(CONCAT_WS('_',(SELECT p.name from sys_provice p where p.id=s.sample_province_id),(SELECT c.name from sys_city c where c.id=s.sample_city_id),(SELECT a.name from sys_area a where a.id=s.sample_area_id))) samplePca";
        
        System.out.println(replace(str));
        
        String st = "(SELECT u.precinct_name from sys_unit u where s.reported_unit_id=u.id) precinct_name";
        
        System.out.println(replace(st));
    }
    

    public static String replace(String str) // 识别括号并将括号内容替换的函数
    {
        int head = str.indexOf('('); // 标记第一个使用左括号的位置
        if (head == -1)
            ; // 如果str中不存在括号,什么也不做,直接跑到函数底端返回初值str
        else {
            int next = head + 1; // 从head+1起检查每个字符
            int count = 1; // 记录括号情况
            do {
                if (str.charAt(next) == '(')
                    count++;
                else if (str.charAt(next) == ')')
                    count--;
                next++; // 更新即将读取的下一个字符的位置
                if (count == 0) // 已经找到匹配的括号
                {
                    String temp = str.substring(head, next); // 将两括号之间的内容及括号提取到temp中
                    str = str.replace(temp, ""); // 用空内容替换,复制给str
                    head = str.indexOf('('); // 找寻下一个左括号
                    next = head + 1; // 标记下一个左括号后的字符位置
                    count = 1; // count的值还原成1
                }
            } while (head != -1); // 如果在该段落中找不到左括号了,就终止循环
        }
        return str; // 返回更新后的str
    }

}

原创粉丝点击