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

2
  • So what's the question? Commented Oct 31, 2016 at 13:49
  • You can try using the SpEL parser of Spring (instead of an if you should use the ternary operator) docs.spring.io/spring/docs/current/spring-framework-reference/… . 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. Commented Nov 1, 2016 at 9:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.