目的: 验证 excel 函数四则运算式的 合法性的 方法,
如 b1+a12*(a1+a2) + round(2/3,2)
如: if( a1!=0,12,34)
校验这个 式子是不是 对的
下面的代码是论坛找的修改了一下,,其实有很多问题,很多情况没考虑到.感觉有些复杂
比如 不是自定义的funcName 函数中的, 这个判断 怎么加到正则里
_ if (/[\+\-\*\/]{1}[^\d\(]/.test(string)) {console.log('运算符后不是数字,也不是自定义的函数'); return false};_
function expressionCheck(string) {
// 先把 A12, ab12 等单元格名称,替换成数字
string = string.replace(/\b[a-z]{1,2}\d{1,2}\b/gi, '1')
const funcName = {
'sum': 1,
'abs': 1,
'round': 1,
};
let stack
// 剔除空白符
string = string.replace(/\s/g, '');
// 错误情况,空字符串
if ("" === string) return false;
// 错误情况,运算符连续
if (/[\+\-\*\/]{2,}/.test(string)) return false;
**错误情况,运算符后不是数字, 不是(, 且不是 funcName中的函数名称 ,这个地方没想到怎么弄???**
if (/[\+\-\*\/]{1}[^\d\(]/.test(string)) {console.log('运算符后不是数字,也不是函数'); return false};
// 错误情况,空括号
if (/\(\)/.test(string)) return false;
// 错误情况,(后面是运算符
if (/\([\+\-\*\/]/.test(string)) return false;
// 错误情况,)前面是运算符
if (/[\+\-\*\/]\)/.test(string)) return false;
// 错误情况,(前面不是运算符
if (/[^\+\-\*\/]\(/.test(string)) return false;
// 错误情况,)后面不是运算符
if (/\)[^\+\-\*\/]/.test(string)) return false;
// 错误情况,括号不配对
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;
}
}
}
// 错误情况,双引号不配对
stack = [];
for (var i = 0, item; i < string.length; i++) {
item = string.charAt(i);
if (item == '"') {
stack.push('"');
}
}
if (0 !== stack.length % 2) return false;
// 错误情况,单引号不配对
stack = [];
for (var i = 0, item; i < string.length; i++) {
item = string.charAt(i);
if (item == "'") {
stack.push("'");
}
}
if (0 !== stack.length % 2) return false;
// 错误情况,不是函数的字符串
const tmpStr = string.replace(/[\(\)\+\-\*\/]{1,}/g, '`');
const array = tmpStr.split('`');
for (let i = 0, item; i < array.length; i++) {
item = array[i];
// 如果是引号中的字符串,忽略掉
if (item.charAt(0) == '"' && item.charAt(item.length - 1) == '"'
|| item.charAt(0) == "'" && item.charAt(item.length - 1) == "'") {
continue
}
if (/[A-Z]/i.test(item) && 'undefined' === typeof (funcName[item])) {
return false;
}
}
console.log('验证成功')
return true;
}
expressionCheck("'我的")