public static String replaceTokens ( String template , Pattern pattern , Map < String , String > replacements ) { StringBuffer sb = new StringBuffer ( ) ; Matcher matcher = pattern . matcher ( template ) ; while ( matcher . find ( ) ) { String replacement = replacements . get ( matcher . group ( 1 ) ) ; if ( replacement == null ) { replacement = "" ; } matcher . appendReplacement ( sb , Matcher . quoteReplacement ( replacement ) ) ; } matcher . appendTail ( sb ) ; return sb . toString ( ) ; }
Matches a template string against a pattern replaces matched tokens with the supplied replacements and returns the result . The regular expression must use a capturing group . The value of the first capturing group is used to look up the replacement . If no replacement is found for the token then it is replaced with the empty string .