基于java中小括号的分组拆分复杂的String

时间:2014-11-17 14:19:54

标签: java regex parsing expression

我有一个来自UI的复杂字符串,如:

(region = "asia") AND ((status = null) OR ((inactive = "true") AND (department = "aaaa")) OR ((costcenter = "ggg") OR (location = "india")))

我需要拆分它并在我的代码中使用它,但我必须考虑括号,以便分组完全如图所示。拆分后,我必须在每次迭代中获得类似下面的内容并将其分解

第一次:

(region = "asia") AND 

((status = null) OR ((inactive = "true") AND (department = "aaaa")) OR ((costcenter = "ggg") OR (location = "india")))

第二次:

(region = "asia") AND 

(

(status = null) OR 

((inactive = "true") AND (department = "aaaa")) OR 
((costcenter = "ggg") OR (location = "india"))

)

依旧......

有关如何实现这一目标的任何指示?

1 个答案:

答案 0 :(得分:0)

因为看起来你不愿意进行全面的解析,正则表达式无法解决这类问题,也许是一个逐步解决方案。

此处解释变量列表,其中 i th 条目的内部文本值为(...),其变量形式为{{1}其中@123123

i

这将给出

static String parse(String exp, List<String> vars) {
    final Pattern BRACED_REDEX = Pattern.compile("\\(([^()]*)\\)");
    for (;;) {
        Matcher m = BRACED_REDEX.matcher(exp);
        if (!m.find()) {
            break;
        }
        String value = m.group(1);
        String var = "@" + vars.size();
        vars.add(value);
        StringBuffer sb = new StringBuffer();
        m.appendReplacement(sb, var);
        m.appendTail(sb);
        exp = sb.toString();
    }
    vars.add(exp); // Add last unreduced expr too.
    return exp;
}

public static void main(String[] args) {
    String exp = "(region = \"asia\") AND ((status = null) OR ((inactive = \"true\") "
        + "AND (department = \"aaaa\")) OR ((costcenter = \"ggg\") OR "
        + "(location = \"india\")))";
    List<String> vars = new ArrayList<>();
    exp = parse(exp, vars);
    System.out.println("Root expression: " + exp);
    for (int i = 0; i < vars.size(); ++i) {
        System.out.printf("@%d = %s%n", i, vars.get(i));
    }
}

对于完整的解决方案,您可以使用Java Scripting API并借用JavaScript引擎或制作自己的小型脚本语言,