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.

- 115,751
- 26
- 228
- 437

- 19
- 4
-
you need more then a regex for that... – snap Mar 02 '18 at 17:04
-
A regex cannot parse JavaScript for validity in any meaningful sense, if thats what your asking. – Alex K. Mar 02 '18 at 17:05
-
What do I need more? – vinny Mar 02 '18 at 17:05
-
I just want to check like a compiler if the user hasn't made any mistakes when he wrote its condition – vinny Mar 02 '18 at 17:07
-
There are lot's of parsers out there, peg.js is an example. https://pegjs.org/ – Keith Mar 02 '18 at 17:08
-
I'm checking this out – vinny Mar 02 '18 at 17:10
1 Answers
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.

- 19,179
- 10
- 84
- 156