62,614
社区成员
发帖
与我相关
我的任务
分享
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);
}
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);
}
}