java中的字符串替换,类似于速度模板 [英] String replacement in java, similar to a velocity template
问题描述
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.
推荐答案
看一下 java.text.MessageFormat
类,MessageFormat获取一组对象,对它们进行格式化,然后将格式化的字符串插入到适当位置的模式中。
Take a look at the java.text.MessageFormat
class, MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.
Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);
这篇关于java中的字符串替换,类似于速度模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!