2

I looked a little over the available parsers on the net but don't really understand what is the most suitable for my custom expression. (Antlr seems a little to heavyweight for my needs, but it's just a first impression)

I have the following expression that needs to be validated that it's well formed:

IF(var1>var2;15;IF(var3<=var4;1;2))

The expression translates to: if the condition is true then the result is 15 else the other expression.

I need only to validate that this is well formed (no extra brackets, that there is always a first and second branch, that the IF keyword is used correctly, nested IFs etc..)

hhh3112
  • 2,167
  • 10
  • 36
  • 55
  • So what's the question? – Theodore Norvell Oct 31 '16 at 13:49
  • You can try using the SpEL parser of Spring (instead of an **if** you should use the ternary operator) http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html . It is as simple as **ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("1+2*(2+7*(1+5))"); System.out.println(exp.getValue());** supports variables and other features. – John Donn Nov 01 '16 at 09:39

1 Answers1

1

First, write a grammar. Otherwise it will be unclear what is legal or not. (What you have written is not precise; for example, are you allowed to have a number after a relational? a variable as the else part of of an IF?) Grammar make this precise.

Second, if your grammar is only going to accept expressions, you can code it easily with a hand-written recursive descent grammar: see my SO answer on how to do this. Such a parser will do all the sanity checking you want.

If you are trying to parse a very complicated language, then JavaCC or ANTLR are better choices.

Community
  • 1
  • 1
Ira Baxter
  • 93,541
  • 22
  • 172
  • 341