2

I have a question about the strsubstitutor with double $$ varible, I have the following code:

Map<String, Object> params = new HashMap<String, Object>();
params.put("hello", "hello");
String templateString = "The ${hello} $${test}.";
StrSubstitutor sub = new StrSubstitutor(params);
String resolvedString = sub.replace(templateString);
System.out.println(resolvedString);

The output is hello ${test}

If the test variable is with double $, and it can not be replaced, why the output is ${test}? Should not be still $${test}?

Makoto
  • 104,088
  • 27
  • 192
  • 230
ratzip
  • 1,571
  • 7
  • 28
  • 53

1 Answers1

3

The reason why $${test} becomes ${test} is that ${...} is a reserved keyword for StrSubstitutor and adding an extra $ in front of it is used to escape it (i.e. if you want to get a literal ${...} in output).

Given that, the documentation says that by default setPreserveEscapes is set to false and this means that:

If set to true, the escape character is retained during substitution (e.g. $${this-is-escaped} remains $${this-is-escaped}). If set to false, the escape character is removed during substitution (e.g. $${this-is-escaped} becomes ${this-is-escaped}). The default value is false

So if you want $${test} in output you should set setPreserveEscapes(true) before replacing the variables.

user2340612
  • 10,053
  • 4
  • 41
  • 66
  • looks like this setPreserveEscapes is deprecated, is there any new function for that to use? – ratzip Aug 12 '19 at 15:42
  • @ratzip actually the entire class is deprecated in favour of [`StringSubstitutor`](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html) – user2340612 Aug 12 '19 at 15:44