【问题标题】:Java strsubstitutor with double $$ varaible具有双 $$ 变量的 Java strsubstitutor
【发布时间】:2019-12-19 04:22:39
【问题描述】:

我对带有双 $$ 变量的 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变量是双$,并且不能被替换,为什么输出是${test}?应该还是$${test}吧?

【问题讨论】:

  • $$ 是一个转义的$,所以它先用{test} 代替它。
  • 对不起,你能解释一下吗

标签: java apache-commons-lang


【解决方案1】:

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

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

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

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

【讨论】:

  • 看起来这个 setPreserveEscapes 已被弃用,有什么新功能可以使用吗?
  • @ratzip 实际上整个类都被弃用了 StringSubstitutor
猜你喜欢
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2013-12-17
  • 2015-07-20
  • 2015-08-25
相关资源
最近更新 更多