FreshRob,
The problem is at what point do you stop doing this replacement strategy. The code you want is actually fairly straightforward to implement, just tedious.
Also, error handling is going to be a pain, as well.
Basically all you need to do is repeatedly recognize against the head of the string, and strip off the part that you've just done, adding it to an output string buffer.
What happens is that users put in strange forms, like the one I showed in the error case of my first post.
So....some basic pseudo-Java code, because I don't have time to write and debug this:
-
String interpolate(String input, Map<String, String>vars)
-
{
-
String in = input;
-
StringBuilder out = new StringBuilder();
-
-
String patVar = "(\\$\\{\\w+\\})";
-
String patStr = "([^$]+)";
-
Pattern p = Pattern.compile("^(" + patStr + "|" +patVar + ")");
-
-
int limit = input.length();
-
while(not in.equals(""))
-
{
-
Matcher m = p.matcher(in);
-
if (not m.matches())
-
throw new Error("Bad input string fella.");
-
-
String bit = m.group(); // grab the matched bit
-
-
int bitLen = bit.length(); // chop off the input bits
-
in = in.substring(bitLen);
-
-
if (bit.charAt(0) != '$')
-
out.append(bit);
-
else if (vars.comtainsKey(bit.substring(2,bitLen-1))
-
out.append(vars(bit.substring(2,bitLen-1));
-
else
-
throw new Error("what is this useless bit: \"" + bit + "\"?");
-
}
-
}
-