Discuss / Java / 追加替换

追加替换

Topic source

此处仅提供 template 的实现

public class Template {
    private final String template;
    private final Pattern pattern = Pattern.compile("\\$\\{(\\w+)}");

    public Template(String template) {
        this.template = template;
    }

    public String render(Map<String, Object> data) {
        Matcher matcher = pattern.matcher(template);
        StringBuilder sb = new StringBuilder();
        while (matcher.find()) {
            Object result = data.get(matcher.group(1));
            if (result != null) {
                // 追加替换
                // 1. 从输入序列中读取字符,从追加位置到匹配位置的开头,并将它们追加到给定的字符串生成器
                // 2. 将给定的替换字符串追加到字符串生成器
                // 3. 将此匹配器的追加位置设置为匹配字符串的结尾再加一
                matcher.appendReplacement(sb, result.toString());
            }
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}

  • 1

Reply