private bool Match() { int index = 0; int exprLength = this._expression.Length; int lKuo = 0; int rKuo = 0; while (index != exprLength) { char who = this._expression[index]; char next = '\0'; if (index != exprLength-1) { next = this._expression[index + 1]; } switch (who) { case '(': if (index == exprLength - 1 || isRightKuo(next) || isSymbol(next)) { return false; } lKuo++; //保证前面的左括号多于右括号 if (rKuo >= lKuo) { return false; } this._elements.Add("("); index++; break; case ')': rKuo++; if (index == exprLength - 1) { this._elements.Add(")"); index++; break; } if (index == 0 || isLeftKuo(next) || isNumber(next)) { return false; } if (rKuo > lKuo) { return false; } this._elements.Add(")"); index++; break; default: //如果是符号类型 if (isSymbol(who)){ if (index == 0 || index == exprLength - 1) { return false; } if (isRightKuo(next) || isSymbol(next)) { return false; } this._elements.Add(who.ToString()); index++; break; } if (!isNumber(who)) { return false; } //剩下为数字,匹配数字的范围 int numberLenth = 0; bool isXiaoShu = false; while (isNumber(this._expression[index + numberLenth]) || this._expression[index + numberLenth] == '.') { if (this._expression[index + numberLenth] == '.') { if (isXiaoShu) { //不能有两个小数点以上 return false; } else { isXiaoShu = true; } } int myIndex = index + numberLenth; numberLenth++; if (myIndex == exprLength - 1) { //最后一个元素 break; } } string num = this._expression.Substring(index, numberLenth); this._elements.Add(num); index += numberLenth; //检查数字的下一个元素 if(index != exprLength) { next = this._expression[index]; } if (isLeftKuo(next)) { return false; } break; } } if (lKuo != rKuo) { return false; } return true; }
向后检查法,只检查当前元素和后面元素的合法性,遍历表达式的每一个元素。
元素类型分为:左括号、右括号,运算符号、数字
左括号,不能是最后一个元素吧。后面不能是右括号和运算符号吧!
右括号,不能是第一个元素吧。后面一定是运算符号吧,其他情况不合格
运算符号,不能是第一和最后一个元素吧。后面不能是运算符号和右括号吧!
数字,后面不能是左括号吧!
匹配元素,主要的就是要把数字匹配出来,只要遇到数字,就一直下一个,直到不是数字为止,注意小数点的出现,只能出现一次,且不是数字的第一位。