Java-提取方括号内的内容(忽略嵌套方括号)? [英] Java - extract content inside square brackets (ignore nested square brackets)?

查看:585
本文介绍了Java-提取方括号内的内容(忽略嵌套方括号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取方括号内的字符串内容(如果一个方括号内包含嵌套的方括号应将其忽略).

I want to extract the string content inside square brackets (if inside one square brackets contains nested square brackets, it should be ignored).

示例:

c[ts[0],99:99,99:99] + 5 - d[ts[1],99:99,99:99, ts[2]] + 5

应返回:

 match1 = "ts[0],99:99,99:99";
 match2 = "ts[1],99:99,99:99, ts[2]";

到目前为止,我的代码仅适用于非嵌套方括号

The code I have so far works only with non-nested square brackets

String in = "c[ts[0],99:99,99:99] + 5 - d[ts[1],99:99,99:99, ts[2]] + 5";

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);

while(m.find()) {
    System.out.println(m.group(1));
}

// print: ts[0, ts[1, 2

推荐答案

不带正则表达式;只是笔直的Java:

Without regex; just straight java:

import java.util.ArrayList;
import java.util.List;

public class BracketParser {

    public static List<String> parse(String target) throws Exception {
        List<String> results = new ArrayList<>();
        for (int idx = 0; idx < target.length(); idx++) {
            if (target.charAt(idx) == '[') {
                String result = readResult(target, idx + 1);
                if (result == null) throw new Exception();
                results.add(result);
                idx += result.length() + 1;
            }
        }
        return results;
    }

    private static String readResult(String target, int startIdx) {
        int openBrackets = 0;
        for (int idx = startIdx; idx < target.length(); idx++) {
            char c = target.charAt(idx);
            if (openBrackets == 0 && c == ']')
                return target.substring(startIdx, idx); 
            if (c == '[') openBrackets++;
            if (c == ']') openBrackets--;
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(parse("c[ts[0],99:99,99:99] + 5 - d[ts[1],99:99,99:99, ts[2]] + 5"));
    }
}

完整GitHub上的代码

这篇关于Java-提取方括号内的内容(忽略嵌套方括号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆