表达式的校验


校验一个运算表达式的格式是否正确

1
var validateExp = function(str){ 2 // str为字符串表达式,里面的内容只能包括运算符(+、-、*、/),还有左右括号,剩下的变量值可以用a-z来表示,如表达式:a+b、(a+b)*c等 3 let operaList = ["+","-","*","/"]; // 运算符 4 let LandOperaList = ["("].concat(operaList); 5 let RandOperaList = [")"].concat(operaList) 6 let validateFlag = true; // 7 let errorTip = ""; //错误信息 8 let strArr = (str||"").trim().replace(/\s/g,"").split("");//整理字符串表达式为数组 9 if(!strArr.length){ 10 return "表达式字符串不可为空" 11 } 12 var leftCount = strArr.filter(one=>{return one=="("}).length; 13 var rightCount = strArr.filter(one=>{return one==")"}).length; 14 if(leftCount!=rightCount){ 15 return "左右括号不成对" 16 } 17 for(var i=0;i<strArr.length;i++){ 18 var value = strArr[i]; 19 var beforeValue = strArr[i-1]; 20 var afterValue = strArr[i+1]; 21 if(value == "("){ 22 if(beforeValue&&LandOperaList.indexOf(beforeValue)<0){ 23 validateFlag = false; 24 errorTip = "第"+Number(i+1)+"个字符:"+value+" 前面不正确" 25 }else if(RandOperaList.indexOf(afterValue)>-1){ 26 validateFlag = false; 27 errorTip = "第"+Number(i+1)+"个字符:"+value+" 后面不正确" 28 }; 29 }else if(value == ")"){ 30 if(LandOperaList.indexOf(beforeValue)>-1){ 31 validateFlag = false; 32 errorTip = "第"+Number(i+1)+"个字符:"+value+" 前面不正确" 33 }else if(afterValue&&RandOperaList.indexOf(afterValue)<0){ 34 validateFlag = false; 35 errorTip = "第"+Number(i+1)+"个字符:"+value+" 后面不正确" 36 }; 37 }else if(operaList.indexOf(value)>-1){ 38 if(LandOperaList.indexOf(beforeValue)>-1){ 39 validateFlag = false; 40 errorTip = "第"+Number(i+1)+"个字符:"+value+" 前面不正确" 41 } else if(RandOperaList.indexOf(afterValue)>-1){ 42 validateFlag = false; 43 errorTip = "第"+Number(i+1)+"个字符:"+value+" 后面不正确" 44 } 45 } else { 46 if(beforeValue&&LandOperaList.indexOf(beforeValue)<-1){ 47 validateFlag = false; 48 errorTip = "第"+Number(i+1)+"个字符:"+value+" 前面不正确" 49 } else if(afterValue&&RandOperaList.indexOf(afterValue)<-1){ 50 validateFlag = false; 51 errorTip = "第"+Number(i+1)+"个字符:"+value+" 后面不正确" 52 } 53 } 54 55 if(!validateFlag){ 56 break; 57 } 58 } 59 if(!validateFlag){ 60 return errorTip 61 } else { 62 return "表达式正确" 63 } 64 }

posted @ 2021-04-21 15:52  蛙仔  阅读(303)  评论(0编辑  收藏  举报