1

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

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);
Varun
  • 5,001
  • 12
  • 54
  • 85
  • 1
    Scan your string character by character maintaining variables such as String currentToken, List tokens, boolean insideBrackets or int bracketDepth. With your basic sample you could also use a regex to extract the tokens, but that will reach its limits when you start nesting brackets – Aaron Feb 04 '20 at 10:20
  • Updated what i was trying – Varun Feb 04 '20 at 10:24

1 Answers1

0

The regex you need is something like this:

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

You can find an example here on regex101.com with explanation.

In Java you have to to match the regex and don't split on it. With the surrounding brackets (\(.*\)|[^\s]+)+ you are creating groups, which can be found like in the following example:

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));
    }
 }
tobsob
  • 602
  • 9
  • 22