如何将运算符上的逻辑表达式拆分为分隔符,同时将它们保留在结果中?

How to Split a logical expression on operators as delimiters, while keeping them in the result?

类似于this question我想拆分我的逻辑表达式 A >= 10 AND B <= 20 OR C in ('3', '4')A>=10ANDB<=20ORCin('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));
    }
 }