bharathi - 10 months ago 55

Java Question

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

I have gone with http://www.sanfoundry.com/java-program-implement-evaluate-expression-using-stacks/

Note: The expression does not contain parenthesis.

For example:

*Valid:*

`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

Answer Source

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
```