如何在运算符(JAVA)上分离布尔表达式?

时间:2016-11-07 21:04:05

标签: java

如何在运算符上分隔布尔表达式? 我将表达式作为以下字符串:

String expression = “((468551X68X304.NAOK == \"2\") and (468551X68X305.NAOK > \"2\") and (468551X68X308.NAOK != \"2000\" or 468551X68X308.NAOK > \"2000\")) “;

我想获取数组中的所有变量,例如:

a[0] = “468551X68X304.NAOK”;
a[1] = “468551X68X305.NAOK”;
a[2] = “468551X68X308.NAOK”;
a[3] = “468551X68X308.NAOK”;

有人可以给我一个解决它的想法吗?

谢谢,

1 个答案:

答案 0 :(得分:0)

这可以使用正则表达式完成。

以下正则表达式匹配格式化的变量,如布尔表达式中的变量:

\d+X\d+X\d+\.NAOK

每个\d+匹配一个或多个数字。

要使用此正则表达式提取变量,您可以使用java.util.regex.Patternjava.util.regex.Matcher,如下所示:

String booleanExpression = "((468551X68X304.NAOK == \"2\") and (468551X68X305.NAOK > \"2\") and (468551X68X308.NAOK != \"2000\" or 468551X68X308.NAOK > \"2000\")) ";
String regex = "\\d+X\\d+X\\d+\\.NAOK"; // Note that backslash pairs don't denote two backslashes here. Because we're representing the regex as a string literal, we have to use escape sequences to represent the backslashes in the regex

Matcher m = Pattern.compile(regex).matcher(booleanExpression);
ArrayList<String> variables = new ArrayList<>();
while(m.find()) // Match a NEW variable (one that wasn't matched in previous iterations
    variables.add(m.group()); // Add the matched variable to the ArrayList