[英]How can i validate a String which includes an Expression/Condition
Hello Community! 你好社区!
I am looking for a way to validate an expression, like a condition in an IF block, that is stored in a string. 我正在寻找一种方法来验证表达式,如IF块中的条件,存储在字符串中。
Example: 例:
expression = "2 + 3 == 5"; //or "true || false == true"
if(validationFunc(expression)){
//do something
}
...
//validates the string and returns a boolean-value
function validationFunc(str) {
//do validation
var regex = /^([\s()!]*(([0-9]+)|(true|false){1})[\s()]*[+\-=\*%!]*)+$/g;
return str.match(regex);
}
There is the possiblity to validate the 'Expression-String' with Regex . 使用Regex验证“Expression-String”是可能的。 I tried to make a Regex-Expression, but it seems to be more complex than i expected. 我试图制作正则表达式,但它似乎比我预期的更复杂。 In addition, I found no solution to this problem in the web. 另外,我在网上找不到解决这个问题的方法。
Has somebody a solution for this problem, or is there a other way to match/validate such a string? 有人为这个问题找到解决方案,还是有其他方法来匹配/验证这样的字符串?
Valid inputs: 有效输入:
true
1 == true
203 == true
0 == false
true == true
true != false
(true && false) || true == true
true == (true && false) || true
20 + 40 == 60
...
Invalid inputs: 输入无效:
empty string
true 0
'' != 20
30 && 4 == true
20 + 3 == false
...
You could use a try ... catch
statement and use the exception for an addtional return. 您可以使用try ... catch
语句并将该异常用于addtional返回。
If wanted, you could return true
(yes, it's an expression), instead of the evaluated value. 如果需要,您可以返回true
(是的,它是表达式),而不是评估值。
function check(expression) { var result; try { result = eval(expression); } catch (error) { return error.toString(); } return result; } var expressions = ['30 && 4 == true', '20 + 3 == false', 'f*ck']; console.log(expressions.map(check));
function isValid(expr) { try { return eval(expr); } catch { return false; } } // Valid ; Correct syntax and return true console.log(isValid(`true`)); console.log(isValid(`true == (true && false) || true`)); // Not valid console.log(isValid(`true 0`)); // Incorrect syntax console.log(isValid(`true === 0`)); // Correct syntax but returns false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.