Java对于成对括号的提取

在工作的项目当中,经运营人员的反馈,发现提供服务的指定属性字段的值为空,导致搜索引擎无法正常搜索到正确的结果。

原始的字符串提取程序为:

// 只取对应符号分割的第一部分
name.split("_|\\(|(")[0].trim();

因此对于"(*)*"之类的字符串,则会提取为相应的空值,所以做了如下优化,提取成对括号中的内容及括号外的内容:

复制代码
// 提取成对括号内的字符串
public static String extractBracketInnerStr(String str) {
        if(!str.contains("(") || !str.contains(")")){
            return "";
        }
        List<String> result = Lists.newArrayList();
        int m = 0, n = 0, count = 0;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == '('){
                if(count == 0) m = i;
                count ++;
            }

            if(str.charAt(i) == ')'){
                count--;
                if (count == 0) {
                    n = i;
                    result.add(str.substring(m+1,n).trim());
                }
            }
        }

        // 检验括号是否配对
        if(count != 0){
            return "";
        }
        return StringUtils.join(" ",result);
    }

    // 提取成对括号外的字符串
    public static String extractBracketOuterStr(String str) {
        if(!str.contains("(") || !str.contains(")")){
            return str;
        }
        List<String> result = Lists.newArrayList();
        int m = 0,n = 0, count = 0;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == '('){
                if(count == 0) {
                    m = i;
                    result.add(str.substring(n,m).trim());
                }
                count ++;
            }

            if(str.charAt(i) == ')'){
                count--;
                if (count == 0) {
                    n = i+1;
                }
            }
        }

        if(n < str.length()){
            result.add(str.substring(n));
        }

        // 检验括号是否配对
        if(count != 0){
            return str;
        }

        return StringUtils.join(" ",result);
    }
复制代码
posted @   mengrennwpu  阅读(4177)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-02-27 IT方面书籍下载整理
点击右上角即可分享
微信分享提示