map中的值替换掉字符串中的变量(含运算)

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.text.StrSubstitutor;

import bsh.Interpreter;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
Test t = new Test();
Map map = new HashMap();
map.put("N1", new Integer(1));
map.put("N2", new Integer(2));
map.put("N3", new Integer(3));
map.put("N4", new Integer(4));
map.put("N5", new Integer(22));
map.put("N6", new Integer(6));
String str = "你好$${${N5}+${N6}-${N4}}";
StrSubstitutor strSubstitutor = new StrSubstitutor(map);
String result = t.operateVariable(strSubstitutor.replace(str),map);
System.out.print(result);
}

public String operateVariable(String str ,Map map){
String result = "";
int begin = 0;
int end = 0;
int count = 0;
String temp = "";
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='$'){
begin = i+2;
result += str.substring(end, i);
}
if(str.charAt(i)=='}'){
end = i+1;
temp = str.substring(begin, i);
Interpreter ii = new Interpreter();
try{
count = ((Integer)ii.eval(temp)).intValue();
}catch(Exception e){
e.printStackTrace();
}
result += count;
}
if(i==str.length()-1){
result += str.substring(end, i+1);
}
}
return result;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值