/**
* 以下两个方法为计算四则运算的方法,用正则
*
* @author 安泳强
* @date Oct 31, 2011 3:39:51 PM
* @param expression
* @return
*/
private String compute(String expression) {
expression = "(" + expression + ")";
String regex = "(.*?)(\\([^()]+\\))(.*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(expression);
while (matcher.find()) {
expression = matcher.group(1) + compute1(matcher.group(2))
+ matcher.group(3);
matcher = pattern.matcher(expression);
// System.out.println(expression);
}
return expression;
}
private String compute1(String expression) {
/*
* 计算没有包含括号的情况下的结果
*/
expression = expression.replaceAll("[( )]", "");
String regex = "^(.*?)(\\d+(?:\\.\\d+)?)([/*])(-?\\d+(?:\\.\\d+)?)(.*)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(expression); double value1 = 0.00; double value2 = 0.00; String temp = null; DecimalFormat df = new DecimalFormat("####################.###"); while (matcher.find()) { value1 = Double.parseDouble(matcher.group(2)); value2 = Double.parseDouble(matcher.group(4)); if (matcher.group(3).equals("*")) { temp = df.format(value1 * value2) + ""; } else { if(value2==0.00){ temp = ""; }else{ temp = df.format(value1 / value2) + ""; } } expression = matcher.group(1) + temp + matcher.group(5); expression = expression.replaceAll("--", "+"); matcher = pattern.matcher(expression); } regex = "^(.*?)((?:(?=[-+*/])-)?\\d+(?:\\.\\d+)?)([-+])(-?\\d+(?:\\.\\d+)?)(.*)"; pattern = Pattern.compile(regex); matcher = pattern.matcher(expression); while (matcher.find()) { value1 = Double.parseDouble(matcher.group(2)); value2 = Double.parseDouble(matcher.group(4)); if (matcher.group(3).equals("+")) { temp = df.format(value1 + value2) + ""; } else { temp = df.format(value1 - value2) + ""; } expression = matcher.group(1) + temp + matcher.group(5); matcher = pattern.matcher(expression); } expression = expression.replaceAll("\\+", ""); return expression; }