繁体   English   中英

动态替换某些字符串的值

[英]Replace certain string's values dynamically

我有一个HashMap<Integer, Double>看起来像这样:{260=223.118,50, 261=1889,00, 262=305,70, 270=308,00}

从数据库中,我取了一个看起来像这样的字符串: String result = "(260+261)-(262+270)";

我想用这些值更改字符串的值 260、261、262...(它们总是与 HashMap 的键相同),这样我就可以得到一个字符串:String finRes = "(223.118,50+1889,00 )-(305,70+308,00)";

此外,字符串结果可以包含乘法和除法字符。

这里一个简单的正则表达式解决方案是将您的输入字符串与模式(\\d+)进行匹配。 这应该产生算术字符串中的所有整数。 然后,我们可以在映射中查找每个匹配项,转换为整数,以获取相应的双精度值。 由于所需的输出又是一个字符串,我们必须将 double 转换回字符串。

Map<Integer, Double> map = new HashMap<>();
map.put(260, 223.118);
map.put(261, 1889.00);
map.put(262, 305.70);
map.put(270, 308.00);

String input = "(260+261)-(262+270)";
String result = input;
String pattern = "(\\d+)";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
StringBuffer sb = new StringBuffer();

while (m.find()) {
    m.appendReplacement(sb, String.valueOf(map.get(Integer.parseInt(m.group(1)))));
}
m.appendTail(sb);
System.out.println(sb.toString());

输出:

(223.118+1889.0)-(305.7+308.0)

演示在这里:

雷克斯特

这是一个解释的解决方案:

    // your hashmap that contains data
    HashMap<Integer,Double> myHashMap = new HashMap<Integer,Double>();
    // fill your hashmap with data ..
    ..
    // the string coming from the Database
    String result = "(260+261)-(262+270)";
    // u will iterate all the keys of your map and replace each key by its value
    for(Integer n : myHashMap.keySet()) {
        result = result.replace(n,Double.toString(myHashMap.get(n)));
    }
    // the String variable 'result' will contains the new String 

希望能帮助到你 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM