Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a set of tokens in a Java String?

I have the following template String: "Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]".

I also have String variables for name, invoice number and due date - what's the best way to replace the tokens in the template with the variables?

(Note that if a variable happens to contain a token it should NOT be replaced).


EDIT

With thanks to @laginimaineb and @alan-moore, here's my solution:

public static String replaceTokens(String text,                                     Map<String, String> replacements) {     Pattern pattern = Pattern.compile("\\[(.+?)\\]");     Matcher matcher = pattern.matcher(text);     StringBuffer buffer = new StringBuffer();      while (matcher.find()) {         String replacement = replacements.get(matcher.group(1));         if (replacement != null) {             // matcher.appendReplacement(buffer, replacement);             // see comment              matcher.appendReplacement(buffer, "");             buffer.append(replacement);         }     }     matcher.appendTail(buffer);     return buffer.toString(); } 
like image 957
Mark Avatar asked Jun 06 '09 14:06

Mark


People also ask

How do you replace a token in a String in Java?

To substitute tokens in a String in Java, we use the Message Format class. The Message Format class provides a means to produce concatenated messages which are not dependent on the language. The Message Format class extends the Serializable and Cloneable interfaces.

How do you replace multiple occurrences of a String in Java?

You can replace all occurrence of a single character, or a substring of a given String in Java using the replaceAll() method of java. lang. String class. This method also allows you to specify the target substring using the regular expression, which means you can use this to remove all white space from String.

How do you replace a specific part of a String in Java?

One of the simplest and straightforward methods of replacing a substring is using the replace, replaceAll or replaceFirst of a String class.

How do you replace all special characters in a String in Java?

String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex. There are two overloaded methods available in Java for replace() : String. replace() with Character, and String.


2 Answers

I really don't think you need to use a templating engine or anything like that for this. You can use the String.format method, like so:

String template = "Hello %s Please find attached %s which is due on %s";  String message = String.format(template, name, invoiceNumber, dueDate); 
like image 151
Paul Morie Avatar answered Oct 16 '22 23:10

Paul Morie


The most efficient way would be using a matcher to continually find the expressions and replace them, then append the text to a string builder:

Pattern pattern = Pattern.compile("\\[(.+?)\\]"); Matcher matcher = pattern.matcher(text); HashMap<String,String> replacements = new HashMap<String,String>(); //populate the replacements map ... StringBuilder builder = new StringBuilder(); int i = 0; while (matcher.find()) {     String replacement = replacements.get(matcher.group(1));     builder.append(text.substring(i, matcher.start()));     if (replacement == null)         builder.append(matcher.group(0));     else         builder.append(replacement);     i = matcher.end(); } builder.append(text.substring(i, text.length())); return builder.toString(); 
like image 44
laginimaineb Avatar answered Oct 16 '22 21:10

laginimaineb