Preface
I believe you may have encountered this situation. When developing similar website letter requirements, we often use string templates, such as
Dear user ${name}. . . . ${name} can be replaced with the user's username.
The following is a simple implementation of this function using regular expressions:
/** * Fill strings according to key-value pairs, such as ("hello ${name}",{name:"xiaoming"}) * Output: * @param content * @param map * @return */ public static String renderString(String content, Map<String, String>> sets = map.entrySet(); for(Entry<String, String> entry : sets) { String regex = "//$//{" + entry.getKey() + "//}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); content = matcher.replaceAll(entry.getValue()); } return content; } The key-value pair is stored in map , and then the key-value pairs are obtained, and the set is traversed to render the string
Example test:
@Test public void renderString() { String content = "hello ${name}, 1 2 3 4 5 ${six} 7, again ${name}. "; Map<String, String> map = new HashMap<>(); map.put("name", "java"); map.put("six", "6"); content = StringHelper.renderString(content, map); System.out.println(content); } There are two variables that need to be replaced, name and six , and the corresponding values are Java and 6 respectively. name is called twice at the same time.
result:
hello java, 1 2 3 4 5 6 7, again java.
Summarize
The above is all about Java using regular expressions to implement the ${name} string template. I hope that the content of this article will be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.