资源简介
java正则实现解析算术表达式 (仅限+-*/和括号)
代码片段和文件信息
import java.util.*;
import java.util.regex.*;
public class expressionParser
{
//解析括号...
public static String parseCurves(String expression){
//构造matcher
String regex=“\\([^\\(\\)]+\\)“;//匹配()
Pattern pattern=Pattern.compile(regex);
Matcher matcher=pattern.matcher(expression);
String finalRes=expression;
while(matcher.find()){
String group=matcher.group();
String result=thenCalculate(priorCalculate(group.substring(1group.length()-1)));
finalRes=matcher.replaceFirst(result);
matcher.reset(finalRes);
}
return finalRes;
}
public static String priorCalculate(String expression){
//单一运算符的计算,先计算*/
String m_dOperate=“([^\\+\\-\\*/]+)([\\*/])([^\\+\\-\\*/]+)“;
Pattern pattern1=Pattern.compile(m_dOperate);
Matcher matcher1=pattern1.matcher(expression);
String finalExp=expression;
while(matcher1.find()){
double d1=Double.parseDouble(matcher1.group(1).trim());
double d2=Double.parseDouble(matcher1.group(3).trim());
String operator=matcher1.group(2);
评论
共有 条评论