Discuss / Java / 作业2

作业2

Topic source

public class Template {

private final String template; private final Pattern p = Pattern.compile("\\$\\{(\\w+)\\}"); public Template(String template) { this.template = template;
    } public String render(Map<String, String> data) {
        Matcher m = p.matcher(template);
        StringBuffer sb = new StringBuffer(); while (m.find()) {
            m.appendReplacement(sb, data.get(m.group(1)));
        }
        m.appendTail(sb); return sb.toString();
    } public static void main(String[] args) {
        Template t = new Template("Hello, ${name}! You are learning ${lang}!");
        Map<String, String> map = Map.of("name", "Bob", "lang", "java");
        String s = t.render(map);
        System.out.println(s);
    }
}


  • 1

Reply