bharathi bharathi - 4 months ago 19
Java Question

validate mathematical variables expression in java

Which is the good way to validate a mathematical variables expression. Whether we can use stack or with regex expression.

I have gone with

Note: The expression does not contain parenthesis.
For example:


  • x+3-y/2

  • x+y

  • 2+4+e


  • x++4+8

  • e-3r

  • e+r34-

How to validate the above expressions?I need to validate the mathematic expression input provided by user in java


If no parentheses (i.e. nesting expressions) are allowed, the validation could be done by simple regex:

final Pattern pattern = Pattern.compile("([0-9]+|[a-z]+)([-+*/]([0-9]+|[a-zAZ]+))*");

for (String s : Arrays.asList("123", "x+3-y/2", "x+y", "2+4+e", "x++4+8", "e-3r", "e+r34-", "---x+3-y/2")) {
    System.out.format("%5s %s\n", pattern.matcher(s).matches(), s);

The output is

 true 123
 true x+3-y/2
 true x+y
 true 2+4+e
false x++4+8
false e-3r
false e+r34-
false ---x+3-y/2