2

我对带有双 $$ 变量的 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}吗?

4

1 回答 1

3

$${test}成为的原因${test}是它${...}是一个保留关键字,StrSubstitutor并在它前面添加一个额外$的用于转义它(即,如果你想${...}在输出中获得文字)。

鉴于此,文档说默认setPreserveEscapes设置为false,这意味着:

如果设置为true,则在替换期间保留转义字符(例如,$${this-is-escaped} 保持为 $${this-is-escaped})。如果设置为false,则在替换过程中会删除转义字符(例如 $${this-is-escaped} 变为 ${this-is-escaped})。默认值为

所以如果你想$${test}在输出中你应该setPreserveEscapes(true)在替换变量之前设置。

于 2019-08-12T15:20:12.187 回答