0

I am working on a project that needs to check if the user has written a good condition on a textfield. So I'd like to know if one of you knows the regex of a 'if'. For example, if the user writes if ((k <= 5 && k>0)|| x>8) I will return true.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
vinny
  • 19
  • 4

1 Answers1

0

Keith's reference looks good (pegjs.org). You're not looking for a regex (albeit possible to do with such) by a lexer + yacc combo (see flex and bison). Note that what you are really looking for is the "expression" parser. A "simple calculator" expression.

One way to test would be to use the "eval()" function. However, it is considered to be a dangerous function. Yet, in your case you let the end user enter an expression and then execute that expression. If they write dangerous stuff, they probably know what they are doing and they will be doing it to themselves.

There is documentation about it:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

In your case you would do something like the following with a try/catch to know whether it is valid:

var valid = true;
try
{
    // where input.val would reference your if() expression
    eval(input.val);
}
catch(e)
{
     valid = false;
}

Note that's a poor man solution since it won't tell you whether other code is included in the expression. There are probably some solution to that such as adding some string at the start such as:

eval("ignore = (1 + " + input.val + ")");

Now input.val pretty much has to be an expression. You'll have to test and see whether that's acceptable or not.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156