Aaron Digulla
Aaron Digulla

Reputation: 328754

Replace variables in text: Suggestions?

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 $).

Upvotes: 2

Views: 1647

Answers (3)

Valentin Rocher
Valentin Rocher

Reputation: 11669

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

Upvotes: 5

Kennet
Kennet

Reputation: 5796

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

Upvotes: 0

dfa
dfa

Reputation: 116382

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();
} 

Upvotes: 1

Related Questions