title: How to replace a set of tokens in a Java String?
body: <p>I have the following template String: <code>"Hello [Name] Please find attached [Invoice Number] which is due on [Due Date]"</code>.</p>
  
  <p>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?  </p>
  
  <p>(Note that if a variable happens to contain a token it should NOT be replaced).</p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>With thanks to @laginimaineb and @alan-moore, <strong>here's my solution:</strong></p>
  
  <pre><code>public static String replaceTokens(String text, 
                                     Map&lt;String, String&gt; 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();
  }
  </code></pre>