Simple, concise Java examples that do useful things.

Thursday, August 24, 2006

Simple template replacer

Often I find I need a simple template engine to replace named regions.



public abstract class Replace {

public static void main(String[] args) {
Replace r = new Replace() {
public String lookup(String key) {
return "*newvalue*";
}
};
String s =
"Welcome ${name}, you have just won a new ${prize}.";
System.out.println(r.replace(s));
}

public String replace(String s) {
return replace(s, 0, new StringBuilder()).toString();
}

private StringBuilder replace(String s, int offset, StringBuilder b) {
int startKey = s.indexOf("${", offset);
if (startKey == -1)
return b.append(s.substring(offset));
else {
b.append(s.substring(offset, startKey));
int keyEnd = s.indexOf('}', startKey);
String key = s.substring(startKey + 2, keyEnd);
b.append(lookup(key));
return replace(s, keyEnd + 1, b);
}
}

abstract public String lookup(String key);
}

No comments: