I had a friend today who asked me to write a regular expression that would verify that a mathematical formula is well-formed.
There are parentheses, variables (unknowns) and operators in the mathematical formula, and the variables are read in the database and can be arbitrarily added and deleted.
This implementation with a regular expression is not possible, so I wrote him a function, as follows:
(function () {/* * if variable selected: ID,NUM,TOTAL,AVL TEST * Correct formula example: id*num+ (TOTAL/AVL) *0.5 * Wrong formula example: id**|0.5 */function fn (String, OBJ) {//TODO: How to handle =? Remove whitespace character string = String.Replace (/\s/g, ');//Error condition, empty string if ("" = = = String) {return false;} Error condition, operator continuous if (/[\+\-\*\/]{2,}/.test (string)) {return false;} Empty parenthesis if (/\ (\)/.test (string)) {return false;} Error conditions, brackets do not match to var stack = [];for (var i = 0, item; i < String.Length; i++) {item = String.charat (i); if (' (' = = = Item) {Stack . Push (' (');} else if (') ' = = = Item} {if (Stack.length > 0) {stack.pop ();} Else{return false;}}} if (0!== stack.length) {return false;} Error condition, (followed by operator if (/\ ([\+\-\*\/]/.test (String)) {return false;} Error condition,) preceded by operator if (/[\+\-\*\/]\)/.test (String)) {return false;} Error condition (not preceded by operator if (/[^\+\-\*\/]\ (/.test (String)) {return false;} Error condition,) is not followed by operator if (/\) [^\+\-\*\/]/.test (String)) {return false;} The error condition, the variable does not come from "to choose Formula variable" var tmpstr = string.replace (/[\ (\) \+\-\*\/]{1,}/g, ""); var array = Tmpstr.split ("); for (var i = 0 , item; i < Array.Length; i++) {Item= Array[i];if (/[a-z]/i.test (item) && ' undefined ' = = = = typeof (Obj[item])) {return false;}} return true;} Test var fields = {' IDs ': 1, ' total ': 1, ' AVL ': 1, ' NUM ': 1}; The string submitted to the server should not contain whitespace characters, or the user should be prevented from entering the white space character alert (FN (' id*num+ (TOTAL/AVL) *0.5 ', fields));}) ();