apache commons-text StringSubstitutor, valueMap.put("amount", 20.0); how to output `$20.0`?

1k Views Asked by At

code:

Map<String, Number> valueMap = new HashMap<>();
valueMap.put("amount", 20.0);
valueMap.put("id", 123456);
StringSubstitutor ss = new StringSubstitutor(valueMap);
// I expect output: $123456===$20.0
System.out.println(ss.replace("${id}===${amount}"));  // output: 123456===20.0
System.out.println(ss.replace("$${id}===$${amount}"));// output: ${id}===${amount}
System.out.println(ss.replace("$$${id}===$$${amount}")); // output: $${id}===$${amount}

I expect output: $123456===$20.0, how to do?

1

There are 1 best solutions below

1
On

You can achieve it by setting an escape char as shown in below example. I have tested it on my local machine and its working as expected:

Map<String, Number> valueMap = new HashMap<>();
valueMap.put("amount", 20.0);
valueMap.put("id", 123456);

StringSubstitutor ss = new StringSubstitutor(valueMap);
ss.setEscapeChar('\\');

System.out.println(ss.replace("$${id}===$${amount}"));  // output: $123456===$20.0

Please refer java docs