javaapache-commons-lang

Java strsubstitutor with double $$ varaible


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}?


Solution

  • 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.