简体   繁体   English

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

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

Similar to this question I want to split my logical expression A >= 10 AND B <= 20 OR C in ('3', '4') to A , >= , 10 , AND , B , <= , 20 , OR , C , in , ('3', '4')这个问题类似,我想将我的逻辑表达式A >= 10 AND B <= 20 OR C in ('3', '4')拆分为A , >= , 10 , AND , B , <= , 20 , OR , C , in , ('3', '4')

how can it be done?怎么做到呢?

I am trying following way(but this doesnt seems to be elegant approach)我正在尝试以下方式(但这似乎不是优雅的方法)

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);

The regex you need is something like this:你需要的正则表达式是这样的:

\(.*\)|[^\s]+

You can find an example here on regex101.com with explanation.您可以在 regex101.com 上找到带有说明的示例。

In Java you have to to match the regex and don't split on it.在 Java 中,您必须匹配正则表达式并且不要对其进行拆分。 With the surrounding brackets (\\(.*\\)|[^\\s]+)+ you are creating groups, which can be found like in the following example:使用周围的括号(\\(.*\\)|[^\\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));
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在运算符上将数学表达式拆分为分隔符,同时将它们保留在结果中? - How to Split a mathematical expression on operators as delimiters, while keeping them in the result? 如何在Java中保留分隔符的同时在不同的分隔符之间拆分文本? - How to split text between different delimiters while keeping delimiters in Java? 正则表达式拆分与分隔符同时保持分隔符 - Regex Split with Delimiters while keeping delimiters 如何通过逻辑运算符(和或)在Java中拆分字符串,但是如果它们出现在引号中则不考虑它们? - How to split a string in java by logical operators (and, or) but not consider them if they appear in quotes? 如何在保留不同分隔符计数的同时拆分字符串? - How to split a string while keeping a count of the different delimiters? 如何拆分字符串,只保留某些分隔符? - How to split a string, keeping only certain delimiters? 如何在 Java 中评估带有逻辑运算符的表达式? - How are expression with logical operators evaluated in Java? 逻辑运算符的正则表达式 - Regular expression for logical operators 如何拆分字符串(基于各种分隔符)但不保留空格? - How to split a string (based on a variety of delimiters) but without keeping whitespace? 如何基于运算符拆分线性String表达式 - How to split a linear String expression on the basis of operators
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM