Replace variables in text: Suggestions?

孤者浪人 提交于 2019-12-07 21:05:53

问题


I'm looking for a nice template engine or short piece of code to expand Ant-like variables in a string in Java. Example:

String result = expand ("${firstName} ${familyName}", map);

It should at least support java.util.Map but something that can handle beans or recursive lookups or lookups in a list of maps/objects would be welcome, too.

Suggestions?

[EDIT] In reply to TofuBeer: No nesting, only valid Java identifiers within the {}. Anything outside of ${} should be copied verbatim. $$ should become $``. If that's not possible ${dollar} should expand to a single $ (so you can express 15.00 $).


回答1:


StrSubstitutor from Commons Lang does pretty much what you're asking for




回答2:


use StringTemplate in order to implement expand:

void expand(String template, Map<String,String> map) {
    StringTemplate st = new StringTemplate(template);

    for (Map.Entry<String, String> attribute : map) {
       st.setAttribute(attribute.getKey(), attribute.getValue());
    }

    return st.toString();
} 



回答3:


Have a look at Freemarker och Velocity, both of them are template engines



来源:https://stackoverflow.com/questions/1872838/replace-variables-in-text-suggestions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!