0

At the moment I work with some logical and mathematical expressions given as a String. Unfortunately, there is a need to use brackets on expressions when using chars: '&' and '|' (used instead of '||').

Valid expressions:

(x + 2) & (y * 4) | (i - 4) (5 > 4) | (6y + 4)

Invalid expressions:

x + 2 & y * 4 | i - 4 5 > 4 | 6y + 4

I have tried to check String with RegEx, something like:

[)][ \t\n\r]*[&][ \t\n\r]*[(] makes sense.

The problem is: how to find all '&' and '|' chars and find presence of near brackets?

Edit: I have a solution based on searching for index of those characters, then going in both ways and looking for brackets. Maybe I can make it in more simple way with RegEx?

designuj
  • 127
  • 1
  • 2
  • 9
  • You need to find or implement a parser for your expression language. Search for "parse expression". Or if look at https://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence – Stephen C May 29 '19 at 06:36
  • does your string also contains **'||'**. – MD Ruhul Amin May 29 '19 at 06:38
  • 1
    Note that parsing expressions using regexes is a bad idea. Either you end up with a horribly complicated regex that supports a recursive expression grammar ... or you have edge cases (complicated expressions) that don't parse when they shoould or vice versa – Stephen C May 29 '19 at 06:39

1 Answers1

0

Relatively simple solution:

  1. split on & and |;
  2. trim all sub-expressions;
  3. check whether they all start with ( and end with ).

Snippet:

String s = "(x + 2) & (y * 4) | (i - 4)";

boolean valid = Arrays.stream(s.split("[&|]"))
                      .map(String::trim)
                      .allMatch(p -> p.startsWith("(") && p.endsWith(")"));

If you need to address more complex scenarios than the ones presented in your question (nested expressions etc.), you'll need to write a parser.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • This won't work if you have nested brackets. (OK ... the OP didn't say he needed this, but I bet that some of his users will expect nested brackets to "just work".) – Stephen C May 29 '19 at 06:41
  • Yep, we use nested brackets. Also comments, variables, booleans... I need to start with something, next steps are on my own :) – designuj May 29 '19 at 06:46
  • Looks like you'll be writing a parser :) – Robby Cornelissen May 29 '19 at 06:51
  • @RobbyCornelissen this solution looks really nice, I need to adjust it because of comments possibility in the end/beginning of expression – designuj May 29 '19 at 07:27