views:

89

answers:

4

Is there is any API which replace template string along with values using Spring or java.

For example:

Dear %FIRST_NAME% %LAST_NAME%,
---- remaining text-----------

where parameters (FIRST_NAME, LAST_NAME) in the form of Map.

A: 

It's relatively simple to write code that will do this. If this is something you're going to be doing a lot however you might want to look into using an existing library like Velocity. It uses a different syntax for values however. See Getting Started.

If you do want to write this yourself try:

public static String replaceAll(String text, Map<String, String> params) {
  return replaceAll(text, params, '%', '%');
}

public static String replaceAll(String text, Map<String, String> params,
    char leading, char trailing) {
  String pattern = "";
  if (leading != 0) {
    pattern += leading;
  }
  pattern += "(\\w+)";
  if (trailing != 0) {
    pattern += trailing;
  }
  Pattern p = Pattern.compile(pattern);
  Matcher m = p.matcher(text);
  boolean result = m.find();
  if (result) {
    StringBuffer sb = new StringBuffer();
    do {
      String replacement = params.get(m.group(1));
      if (replacement == null) {
        replacement = m.group();
      }
      m.appendReplacement(sb, replacement);
      result = m.find();
    } while (result);
    m.appendTail(sb);
    return sb.toString();
  }
  return text;
}

For example:

String in = "Hi %FIRST_NAME% %LAST_NAME%.";
Map<String, String> params = new HashMap<String, String>();
params.put("FIRST_NAME", "John");
params.put("LAST_NAME", "Smith");
String out = replaceAll(in, params);
System.out.println(out);

Output:

Hi John Smith.
cletus
A: 

Check StringTemplate, http://www.stringtemplate.org/ and article here to get feel of it, http://www.codecapers.com/post/Generating-Structured-Text-with-StringTemplate.aspx

Adi
A: 

My favorite templating engine is Apache Velocity

Integrates nicely with Spring as well, theres an introductory article here

objects