1.  请教一段java正则表达式代码
需求如下:
把一个公式中的内容进行替换
1.首先定义一些变量,如:
a=2;
b=3;
aa=4;
bb=5;
ab=6;
2.再写一个公式
String formula = (a+b+aa-bb+ab)*a;
3.现在要计算这个公式的值.
我的需求只要把这个公式转成 (2+3+4+5+6)*2 就可以了.
4.我现在只会用简单的
 formula = formula.replaceAll("a", 2);
formula = formula.replaceAll("b", 3);
formula = formula.replaceAll("aa", 4);
formula = formula.replaceAll("bb", 5);
formula = formula.replaceAll("ab", 6);
这样有时候是可以,但遇到 aa 里面包含 a 时就错了.如果这样写的话就会变成了 
(2+3+22-33+23)*2.
5.后来我又想用正则表达式,写成下面这样.
public static String regexReplace(String formula) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("a", "2");
hm.put("b", "3");
hm.put("aa", "4");
hm.put("bb", "5");
hm.put("ab", "6");
String regEx = null;
Pattern p = null;
Matcher m = null;
for (Iterator<Map.Entry<String, String>> it = hm.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> e = (Map.Entry<String, String>) it.next();
------------------------------------------------------------------------------
regEx = "[+,-,*,/,(,)]{0,1}" + e.getKey() + "[+,-,*,/,(,)]{0,1}"; 这个正则表达式我不会写,请高手赐教,先拜谢了
------------------------------------------------------------------------------
p = Pattern.compile(regEx);
m = p.matcher(formula);
formula = m.replaceAll(e.getValue()); 
System.out.println(formula);
}
return formula;
}

解决方案 »

  1.   

    public class Test {
    public static void main(String[] args) throws Exception {
    int a=2; 
    int b=3; 
    int aa=4; 
    int bb=5; 
    int ab=6;
    String str="(a+b+aa-bb+ab)*a";
    Pattern p = Pattern.compile("[a-z]++");
    Matcher m=p.matcher(str);
    while(m.find()){
    String group = m.group();
    if("a".equals(group)){
    str=str.replaceFirst("a", a+"");
    }else if("b".equals(group)){
    str=str.replaceFirst("b", b+"");
    }else if("aa".equals(group)){
    str=str.replaceFirst("aa", aa+"");
    }else if("bb".equals(group)){
    str=str.replaceFirst("bb", bb+"");
    }else if("ab".equals(group)){
    str=str.replaceFirst("ab", ab+"");
    }
    }
    System.out.println(str);
    }
    }运行结果为(2+3+4-5+6)*2
    千万别直接写str.replace("a",a+"");这样会将所有的"a"替换掉,包括"aa","ab"中的
      

  2.   

    throws Exception 是我写其他代码用的,应该删掉的,忘了
      

  3.   

    谢谢楼上,非常完美,结贴给分.
    最终结果 public static void FinalReplace() {
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("a", "2");
    hm.put("b", "3");
    hm.put("aa", "4");
    hm.put("bb", "5");
    hm.put("ab", "6");
    String str = "(a+b+aa-bb+ab)*a+bb+ab";
    Pattern p = Pattern.compile("[a-z]++");
    Matcher m = p.matcher(str);
    String key = null;
    String value = null;
    while (m.find()) {
    String group = m.group();
    for (Iterator<Map.Entry<String, String>> it = hm.entrySet().iterator(); it.hasNext();) {
    Map.Entry<String, String> e = (Map.Entry<String, String>) it.next();
    key = e.getKey();
    value = e.getValue();
    str = str.replaceFirst(key, value);
    }
    }
    System.out.println(str);
    }