RT,最近又看了下JAVA的正则式,解决了之前对JAVA中正则式的一些疑问.
写了个利用正则式计算表达式值的代码.算法很简单,就是"先乘除,后加减,有括号先算括号里的"
ps:当然,计算表达式值最常用也最有效的方法是利用逆波兰式,这儿只是拿正则式来练练手.
程序没有经过严谨的测试,可能有bug.
java 代码
- import java.util.regex.*;
- import java.util.*;
- /**
- *利用正则式计算表达式的值
- *@author: Eastsun
- *@version: 0.5 07.2.26
- */
- public class Calculate{
- /*
- 正则式这块贴上来会影响代码结构,略之.
- 详见打包后的代码
- */
- private static double operator(Matcher m, int index){
- index =index* 2 ;
- double a,b;
- if (m.group( 1 )!= null ){
- a =Double.parseDouble(m.group( 1 ));
- b =Double.parseDouble(m.group( 2 ));
- }
- else {
- index ++;
- a =Double.parseDouble(m.group( 3 ));
- b =Double.parseDouble(m.group( 4 ));
- }
- double r = 0.0 ;
- switch (index){
- case 0 :
- r =a+b;
- break ;
- case 1 :
- r =a-b;
- break ;
- case 2 :
- r =a*b;
- break ;
- case 3 :
- r =a/b;
- break ;
- }
- return r;
- }
- public static double eval(String str){
- StringBuilder sb = new StringBuilder(str.replaceAll( "\\s+" , "" ));
- while ( true ){
- Matcher m =BRA.matcher(sb);
- if (m.find()){
- sb.replace(m.start(),m.end(),m.group( 1 ));
- }
- else {
- int index = 1 ;
- m =MUL_OR_DIV.matcher(sb);
- if (!m.find()){
- index --;
- m =ADD_OR_SUB.matcher(sb);
- if (!m.find()) break ;
- }
- sb.replace(m.start(),m.end(), "" +operator(m,index));
- }
- }
- return Double.parseDouble(sb.toString());
- }
- public static void main(String[] args){
- Scanner scan = new Scanner(System.in);
- while ( true ){
- System.out.print( "\nEnter a expression :" );
- String str =scan.next();
- if (str.equals( "exit" )) break ;
- System.out.print(str + " = " +eval(str));
- }
- }
- }