Java 带有双 $$ 变量的 strsubstitutor

Java strsubstitutor with double $$ varaible

我对带有双 $$ 变量的 strsubstitutor 有疑问,我有以下代码:

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);

输出为hello ${test}

如果test变量是double $,而且不能替换,为什么输出是${test}?不应该还是$${test}?

之所以$${test}变成${test}是因为${...}StrSubstitutor的保留关键字,前面多加了一个$是用于转义它(即如果你想在输出中获得文字 ${...})。

鉴于此,the documentation 表示默认情况下 setPreserveEscapes 设置为 false,这意味着:

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

因此,如果您希望输出 $${test},则应在替换变量之前设置 setPreserveEscapes(true)