这是最近在项目中的一个需求,已知a=3,求字符串"a<=2"的值,也就是应该返回false。这个问题可大可小,就我们的应用场景也就是用来让用户自定义变量区间,比如类似下面这样的规则:
a<=2 返回积分系数1.0
2<a<=5 返回积分系数1.1
a>5 返回积分系数1.2
如果用switch写死在代码中,以后要修改规则实在是很麻烦的事情,用户也希望能自己维护这样些区间值。于是我想就让用户自己输入这样的表达式和变量的值保存在数据库中,然后计算的时候由系统来解析表达式并求值。问题就归结到求值字符串型逻辑表达式。这个问题恰好是规则引擎的应用领域,可我们的系统已经上线蛮久了,从维护角度也不希望再引入新的开源工具,况且也就这么一个地方用到。如果是算术表达式(比如2+3之类)可以直接扔进数据库执行即可,逻辑表达式倒是可以通过调用脚本语言来eval,但是同样是考虑后期维护问题,也不想引入beanshell、groovy的脚本语言。所以,我就自己写了个parser用于求值。
基本原理就是维护两个栈:操作数栈和操作符号栈,解析和求值的过程就是入栈和出栈操作。首先使用arraylist实现一个栈,很容易的事情:
class stack {
protected java.util.arraylist pool = new java.util.arraylist();
public stack() {
}
public stack(int n) {
pool.ensurecapacity(n);
public void clear() {
pool.clear();
public boolean isempty() {
return pool.isempty();
public int size() {
return pool.size();
public object topel() {
if (isempty())
throw new java.util.emptystackexception();
return pool.get(pool.size() - 1);
public object pop() {
return pool.remove(pool.size() - 1);
public void push(object el) {
pool.add(el);
public string tostring() {
return pool.tostring();
}
然后看看expressionparser.java,原理已经列上,注释也有,使用了单例模式,就请自己看了:
package net.rubyeye.codelib.util;
/**
* <p>类说明:用于表达式与实际值的比较</p>
* <p>注意事项:</p>
* <pre></pre>
* <p>创建日期:aug 6, 2007 10:18:58 am</p>
* <p>文件名:expressionparser.java</p>
* @author:庄晓丹
* @version $id:$
*/
public class expressionparser {
private static final boolean debug = true;
private static expressionparser parser = new expressionparser();
private expressionparser() {
public static expressionparser getinstance() {
return parser;
public boolean firerule(string expression, double fact) {
tracecalculate("\nexpression:" + expression);
expression = expression.replace("\n|\r", "").trim();
char[] chars = expression.tochararray();
return parseexpression(fact, chars);
/**
* @param fact
* @param operatorsstack
* @param operandsstack
* @param chars
* @param operand
* @param operator
* @return
*/
private boolean parseexpression(double fact, char[] chars) {
boolean result = true;
string operand = "";
string operator = "";
stack operatorsstack = new stack();
stack operandsstack = new stack();
for (int i = 0; i < chars.length; i++) {
char token = chars[i];
tracecalculate("token:" + token);
if (character.isdigit(token) || token == '.') {
if (!operator.equals("")) {
tracecalculate("push operator:" + operator);
// 将操作符放入操作符号栈
operatorsstack.push(operator);
operator = "";
}
operand += token;
result = checktail(fact, operatorsstack, operandsstack,
chars.length, operand, result, i);
continue;
} else if (character.isletter(token)) {
operand = string.valueof(token);
//将操作数放入操作数栈
operandsstack.push(operand);
tracecalculate("push operand:" + token);
operand = "";
} else {
if (!operatorsstack.isempty() && !operandsstack.isempty()) {
//当前操作数是字母(变量),已存入栈,因此需要取出
if (operand.equals("")) {
operand = (string) operandsstack.pop();
result = result
&& calculateperfomance(operatorsstack,
operandsstack, operand, fact);
//当前操作数是数字
} else {
}
if (!operand.equals("")) {
result = checktail(fact, operatorsstack, operandsstack,
chars.length, operand, result, i);
//将操作数放入操作数栈
operandsstack.push(operand);
tracecalculate("push2 operand:" + operand);
operand = "";
operator += token;
}
}
return result;
* 判断是否已经到表达式尾端,如果是,计算
* @param result
* @param i
private boolean checktail(double fact, stack operatorsstack,
stack operandsstack, int chars_length, string operand,
boolean result, int i) {
if (i == chars_length - 1) {
result = result
&& calculateperfomance(operatorsstack, operandsstack,
operand, fact);
private void displaystack(string name,stack stack) {
if (debug) {
for (int i = 0; i < stack.pool.size(); i++)
system.out.println(name+stack.pool.get(i));
private boolean calculateperfomance(stack operatorsstack,
stack operandsstack, string currentoperand, double fact) {
tracecalculate("开始计算");
displaystack("operators stack:",operatorsstack);
displaystack("operands stack:",operandsstack);
tracecalculate("currentoperand=" + currentoperand);
string operator = (string) operatorsstack.pop();
double lastoperand = coveroperandtodouble((string) operandsstack.pop(),
fact);
double nextoperand = coveroperandtodouble(currentoperand, fact);
if (operator.equals("=="))
return lastoperand == nextoperand;
if (operator.indexof("=") >= 0)
hasequal = true;
char[] operators = operator.tochararray();
for (int i = 0; i < operators.length; i++) {
switch (operators[i]) {
case '<':
result = result && (lastoperand < nextoperand);
break;
case '=':
//result为false,也就是小于,大于符号不满足的时候,判断等号是否成立
if (!result)
result = (lastoperand == nextoperand);
case '>':
result = result && (lastoperand > nextoperand);
if ((!result) && hasequal)
result = lastoperand == nextoperand;
* 用于debug
private void tracecalculate(string info) {
if (debug)
system.out.println(info);
private double coveroperandtodouble(string operand, double fact) {
//如果是字母,也就是变量,返回fact变量
if (character.isletter(operand.tochararray()[0]))
return fact;
else
return double.parsedouble(operand);
通过debug变量来决定是否输出计算过程,你可以设置为true来看看某个表达式的计算过程。附上单元测试来看看怎么用:
* 测试表达式计算
import junit.framework.testcase;
public class expressioncalculatetest extends testcase {
string exp1,exp2,exp3, exp4;
double v1, v2, v3, v4, v5;
expressionparser parser = null;
protected void setup() throws exception {
exp1 = "a<80";
exp2 = "80<=a<81";
exp3 = "81<=a<=82";
exp4 = "a>=90";
v1 = 70.0;
v2 = 81.2;
v3 = 80;
v4 = 90;
v5 = 92;
parser = expressionparser.getinstance();
public void testfirerule() throws exception {
assertfalse(parser.firerule(exp1, v4));
asserttrue(parser.firerule(exp1, v1));
assertfalse(parser.firerule(exp1, v3));
assertfalse(parser.firerule(exp2, v2));
asserttrue(parser.firerule(exp2, v3));
assertfalse(parser.firerule(exp2, 82));
asserttrue(parser.firerule(exp3, v2));
asserttrue(parser.firerule(exp4, v4));
assertfalse(parser.firerule(exp4, v1));
asserttrue(parser.firerule(exp4, v5));
asserttrue(parser.firerule("b==100.00", 100.0));
asserttrue(parser.firerule("c==0.00", 0));
asserttrue(parser.firerule("60<=c<=80", 79.9));
assertfalse(parser.firerule("60<=50<=80", 0.0));
asserttrue(parser.firerule("60<=79<=80", 0.0));
assertfalse(parser.firerule("60<=99<=80", 0.0));
asserttrue(parser.firerule("60<=80<=90<100", 0.0));
assertfalse(parser.firerule("60<=99<=80<100", 0.0));
asserttrue(parser.firerule("10=<a=<30", 25));
这个小程序对处理一般的类似区间的规则计算应该还有点用,希望对别人帮助吧。表达式中的逻辑运算符>=和<=可以用=>和=<替代。
文章转自庄周梦蝶 ,原文发布时间2007-08-06