-2

I have a textfield, where a user can write a mathamatical expression which may include if-else block.

So, an expressions can be as follows,

a * b // here there is space between a and *

p+q // here there is no space between p and +

x+ y // here there is no space between x & + bu there in between + & y

(x+y)(x*y)

if(a>10){a+b}else if(b>10){b-a}else{a+b}

if( age>18 ){ a+90 }else{ a-90 } // spaces may present or not

if( married == "yes"){ total*0.1 } else{ total*0.2 } // spaces may present or not

These all above examples are valid expression.

I am trying to validate all these types of expression with single regular expression. How a regular expression look like in JavaScript?

Thank you :)

Prashant Shilimkar
  • 8,402
  • 13
  • 54
  • 89

1 Answers1

2

You cannot do this with regular expressions. The main problem is that you cannot check that arbitrary levels of nested parentheses, brackets, braces, etc. are balanced. (See the answers to this thread for more info.)

Handling optional white space is easy in a regex; just use \s* every place that optional white space is allowed and use \s+ wherever white space is required (e.g., to separate words—such as else\s+if, where there must be at least one and possibly more white space characters between the "else" and the "if").

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521