类似于this question我想拆分我的逻辑表达式
A >= 10 AND B <= 20 OR C in ('3', '4')
至A
, >=
, 10
, AND
, B
, <=
, 20
, OR
, C
, in
, ('3', '4')
如何才能做到?
我正在尝试以下方式(但这似乎不是一个优雅的方法)
String orRules[] = inputRule.split(" OR ");
for (int i = 0; i < orRules.length; i++) {
String andRules[] = orRules[i].split(" AND ");
for (int j = 0; j < andRules.length; j++) {
String[] result = andRules[j].split("(?<=[-+*/])|(?=[-+*/])");
System.out.println(Arrays.toString(result));
}
orRules[i] = String.join(" AND ", andRules);
}
output = String.join(" OR ", orRules);
最佳答案
您需要的正则表达式是这样的:
\(.*\)|[^\s]+
你可以找到一个例子here on regex101.com并附有解释。
在 Java 中,您必须匹配正则表达式,并且不要对其进行拆分。
使用括弧 (\(.*\)|[^\s]+)+
您可以创建组,如下例所示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
public static void main(String[] args) {
String ex = "A >= 10 AND B <= 20 OR C in ('3', '4')";
String regex ="(\\(.*\\)|[^\\s]+)+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(ex);
while(m.find()) {
System.out.println(m.group(1));
}
}
关于java - 如何将运算符的逻辑表达式拆分为分隔符,同时将它们保留在结果中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60054933/