根据java中小括号的分组拆分复杂的String

我有一个来自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")) ) 

等等…

关于如何实现这一点的任何指针?

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

这里解释变量列表,其中第i 条目具有(...)的内部文本值,其中forms为@123变量,其中123i

 static String parse(String exp, List 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 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)); } } 

这会给

 Root expression: @0 AND @8 @0 = region = "asia" @1 = status = null @2 = inactive = "true" @3 = department = "aaaa" @4 = @2 AND @3 @5 = costcenter = "ggg" @6 = location = "india" @7 = @5 OR @6 @8 = @1 OR @4 OR @7 @9 = @0 AND @8 

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