java中的字符串替换,类似于velocity模板 [英] String replacement in java, similar to a velocity template
本文介绍了java中的字符串替换,类似于velocity模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java 中是否有任何 String
替换机制,我可以在其中传递带有文本的对象,并在字符串出现时替换它.
例如,文字是:
Is there any String
replacement mechanism in Java, where I can pass objects with a text, and it replaces the string as it occurs.
For example, the text is :
Hello ${user.name},
Welcome to ${site.name}.
我拥有的对象是 "user"
和 "site"
.我想用对象中的等效值替换 ${}
中给出的字符串.这与我们替换速度模板中的对象相同.
The objects I have are "user"
and "site"
. I want to replace the strings given inside ${}
with its equivalent values from the objects. This is same as we replace objects in a velocity template.
推荐答案
使用 Apache Commons Text 中的 StringSubstitutor
.
Use StringSubstitutor
from Apache Commons Text.
https://commons.apache.org/proper/commons-text/
它会为你做这件事(以及它的开源......)
It will do it for you (and its open source...)
Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
这篇关于java中的字符串替换,类似于velocity模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文