if an attribute is not present in map, How to replace the values in template string using strsubsitutor as null or empty string

huangapple go评论72阅读模式
英文:

if an attribute is not present in map, How to replace the values in template string using strsubsitutor as null or empty string

问题

我有一个字符串

    String templateString = "The ${animal} jumps over the ${target}.";
    valuesMap.put("animal", "quick brown fox");
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    String resolvedString = sub.replace(templateString);

但是在 valuesMap 中没有 target 属性的条目。
最终的 resolvedString 应该是
The quick brown fox jumps over the ${target}。

而不是 ${target},它应该是空的。模板字符串中没有在映射中找到键的值应该为空或为 null。

所需的结果是
The quick brown fox jumps over the。

如何处理这种情况
英文:

I have a string

String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

But there is no entry for attr target in valuesMap.
Final resolvedString would be
The quick brown fox jumps over the ${target}.

Instead of ${target}, it need to be empty. Values in templatestring which doesn't have key in map should be empty or null.

required
The quick brown fox jumps over the.

How to handle this

答案1

得分: 1

您的Map<String, String> valuesMap仅包含键值对"animal", "quick brown fox",您需要向映射中添加键值对"target", "",操作如下所示:

String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", ""); //<-- 将新的键值对添加到映射中
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
英文:

Your Map&lt;String,String&gt; valuesMap contains just the couple key, value &quot;animal&quot;, &quot;quick brown fox&quot;, you have to add the couple &quot;target&quot;, &quot;&quot; to your map like below:

String templateString = &quot;The ${animal} jumps over the ${target}.&quot;;
valuesMap.put(&quot;animal&quot;, &quot;quick brown fox&quot;);
valuesMap.put(&quot;target&quot;, &quot;&quot;); //&lt;-- adding the new couple to the map
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

huangapple
  • 本文由 发表于 2020年9月8日 16:31:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63790095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定