Java字符串模板替换(模板渲染)

http://www.dutycode.com/post-168.html

java渲染字符串模板,也就是说在java字符串模板中设置变量字符串,使用变量去渲染指定模板中设置好的变量字符串。下面介绍4种替换模板方式:

1、使用内置String.format

String message = String.format("您好%s,晚上好!您目前余额:%.2f元,积分:%d", "张三", 10.155, 10);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10

2、使用内置MessageFormat 

String message = MessageFormat.format("您好{0},晚上好!您目前余额:{1,number,#.##}元,积分:{2}", "张三", 10.155, 10);
System.out.println(message);
//您好张三,晚上好!您目前余额:10.16元,积分:10

3、使用自定义封装 

。。。。。
private static Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
。。。。。public static String processTemplate(String template, Map<String, Object> params){
    StringBuffer sb = new StringBuffer();
while (m.find()) {
        String param = m.group();
        Object value = params.get(param.substring(2, param.length() - 1));
        m.appendReplacement(sb, value==null ? "" : value.toString());
    }
    m.appendTail(sb);
    return sb.toString();
}
 
public static void main(String[] args){
    Map map = new HashMap();
    map.put("name", "张三");
    map.put("money", String.format("%.2f", 10.155));
    map.put("point", 10);
    message = processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map);
    System.out.println(message);
    //您好张三,晚上好!您目前余额:10.16元,积分:10
}
 


4、使用模板引擎freemarker 

首先引入freemarker.jar,这里以2.3.23版本为例,如果使用maven的配置pom.xml

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>
try {
    map = new HashMap();
    map.put("name", "张三");
    map.put("money", 10.155);
    map.put("point", 10);
    Template template = new Template("strTpl", "您好${name},晚上好!您目前余额:${money?string(\"#.##\")}元,积分:${point}", new Configuration(new Version("2.3.23")));
    StringWriter result = new StringWriter();
    template.process(map, result);
    System.out.println(result.toString());
    //您好张三,晚上好!您目前余额:10.16元,积分:10
}catch(Exception e){
    e.printStackTrace();
}
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
 
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * Created by cxq on 2018-01-07.
 */
public class Tpl {
 
    public static Configuration cfg;
 
    static {
        cfg = new Configuration(new Version("2.3.23"));
    }
 
    public static void main(String[] args) {
        Object[] obj = new Object[]{"张三", String.format("%.2f", 10.155), 10};
        System.out.println(processFormat("您好%s,晚上好!您目前余额:%s元,积分:%d", obj));
        System.out.println(processMessage("您好{0},晚上好!您目前余额:{1}元,积分:{2}", obj));
 
        Map map = new HashMap();
        map.put("name", "张三");
        map.put("money", String.format("%.2f", 10.155));
        map.put("point", 10);
        System.out.println(processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
        System.out.println(processFreemarker("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
    }
 
    /**
     * String.format渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processFormat(String template, Object... params) {
        if (template == null || params == null)
            return null;
        return String.format(template, params);
    }
 
    /**
     * MessageFormat渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processMessage(String template, Object... params) {
        if (template == null || params == null)
            return null;
        return MessageFormat.format(template, params);
    }
 
    /**
     * 自定义渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processTemplate(String template, Map<String, Object> params) {
        if (template == null || params == null)
            return null;
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }
 
    /**
     * Freemarker渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processFreemarker(String template, Map<String, Object> params) {
        if (template == null || params == null)
            return null;
        try {
            StringWriter result = new StringWriter();
            Template tpl = new Template("strTpl", template, cfg);
            tpl.process(params, result);
            return result.toString();
        } catch (Exception e) {
            return null;
        }
    }
 
}

综合,完整示例:

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
 
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * Created by cxq on 2018-01-07.
 */
public class Tpl {
 
    public static Configuration cfg;
 
    static {
        cfg = new Configuration(new Version("2.3.23"));
    }
 
    public static void main(String[] args) {
        Object[] obj = new Object[]{"张三", String.format("%.2f", 10.155), 10};
        System.out.println(processFormat("您好%s,晚上好!您目前余额:%s元,积分:%d", obj));
        System.out.println(processMessage("您好{0},晚上好!您目前余额:{1}元,积分:{2}", obj));
 
        Map map = new HashMap();
        map.put("name", "张三");
        map.put("money", String.format("%.2f", 10.155));
        map.put("point", 10);
        System.out.println(processTemplate("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
        System.out.println(processFreemarker("您好${name},晚上好!您目前余额:${money}元,积分:${point}", map));
    }
 
    /**
     * String.format渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processFormat(String template, Object... params) {
        if (template == null || params == null)
            return null;
        return String.format(template, params);
    }
 
    /**
     * MessageFormat渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processMessage(String template, Object... params) {
        if (template == null || params == null)
            return null;
        return MessageFormat.format(template, params);
    }
 
    /**
     * 自定义渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processTemplate(String template, Map<String, Object> params) {
        if (template == null || params == null)
            return null;
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value == null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }
 
    /**
     * Freemarker渲染模板
     * @param template 模版
     * @param params   参数
     * @return
     */
    public static String processFreemarker(String template, Map<String, Object> params) {
        if (template == null || params == null)
            return null;
        try {
            StringWriter result = new StringWriter();
            Template tpl = new Template("strTpl", template, cfg);
            tpl.process(params, result);
            return result.toString();
        } catch (Exception e) {
            return null;
        }
    }
 
}

http://www.weizhixi.com/user/index/article/id/53.html

/** 
    * 简单实现${}模板功能 
    * 如${aa} cc ${bb} 其中 ${aa}, ${bb} 为占位符. 可用相关变量进行替换 
    * @param templateStr 模板字符串 
    * @param data     替换的变量值 
    * @param defaultNullReplaceVals  默认null值替换字符, 如果不提供, 则为字符串"" 
    * @return 返回替换后的字符串, 如果模板字符串为null, 则返回null 
    */  
      
@SuppressWarnings("unchecked")  
public static String simpleTemplate(String templateStr, Map<String, ?> data, String... defaultNullReplaceVals) {  
    if(templateStr == null) return null;  
      
    if(data == null) data = Collections.EMPTY_MAP;  
          
    String nullReplaceVal = defaultNullReplaceVals.length > 0 ? defaultNullReplaceVals[0] : "";  
    Pattern pattern = Pattern.compile("\\$\\{([^}]+)}");  
          
    StringBuffer newValue = new StringBuffer(templateStr.length());  
  
    Matcher matcher = pattern.matcher(templateStr);  
  
    while (matcher.find()) {  
        String key = matcher.group(1);  
        String r = data.get(key) != null ? data.get(key).toString() : nullReplaceVal;  
        matcher.appendReplacement(newValue, r.replaceAll("\\\\", "\\\\\\\\")); //这个是为了替换windows下的文件目录在java里用\\表示  
    }  
  
    matcher.appendTail(newValue);  
  
    return newValue.toString();  
}  
  
//测试方法    
public static void main(String[] args) {  
    String tmpLine = "简历:\n 姓名: ${姓} ${名} \n 性别: ${性别}\n 年龄: ${年龄} \n";  
    Map<String, Object> data = new HashMap<String, Object>();  
    data.put("姓", "wen");  
    data.put("名", "66");  
    data.put("性别", "man");  
    data.put("年龄", "222");  
          
    System.out.println(simpleTemplate(tmpLine, null, "--"));  
}

http://wen66.iteye.com/blog/830526

 

static final String jsonStr = "{\"name\":\"11\",\"time\":\"2014-10-21\"}";
static final String template = "亲爱的用户${name},你好,上次登录时间为${time}";

static String generateWelcome(String jsonStr,String template){
    Gson gson = new Gson();
    HashMap jsonMap = gson.fromJson(jsonStr, HashMap.class);
    for (Object s : jsonMap.keySet()) {
        template = template.replaceAll("\\$\\{".concat(s.toString()).concat("\\}")
                , jsonMap.get(s.toString()).toString());
    }
    return template;
}

public static void main(String[] args) throws IOException {
    System.out.println(generateWelcome(jsonStr,template));
}

https://segmentfault.com/q/1010000002484866

在开发中类似站内信的需求时,我们经常要使用字符串模板,比如

尊敬的用户${name}。。。。

里面的${name}就可以替换为用户的用户名。

下面使用正则表达式简单实现一下这个功能:

/**
     * 根据键值对填充字符串,如("hello ${name}",{name:"xiaoming"})
     * 输出:
     * @param content
     * @param map
     * @return
     */
    public static String renderString(String content, Map<String, String> map){
        Set<Entry<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;
    

在map里存储了键值对,然后获取键值对的集合,遍历集合进行对字符串的渲染

测试:

    @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);
    }
有两个变量需要替换,name和six,对应的值分别为java和6,同时name调用了两次。

结果:

hello java, 1 2 3 4 5 6 7, again java. 

 http://www.zgljl2012.com/javazheng-ze-biao-da-shi-shi-xian-name-xing-shi-de-zi-fu-chuan-mo-ban/

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 以下是一个基本的 Java Markdown 模板,你可以在其中添加你自己的 Markdown 渲染代码: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.commonmark.node.*; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; public class MarkdownTemplate { public static void main(String[] args) throws IOException { String markdown = new String(Files.readAllBytes(Paths.get("example.md"))); Parser parser = Parser.builder().build(); Node document = parser.parse(markdown); HtmlRenderer renderer = HtmlRenderer.builder().build(); System.out.println(renderer.render(document)); } } ``` 在这个模板中,我们首先读取了一个 Markdown 文件,然后使用 CommonMark 库将其解析为一个 AST(抽象语法树)对象,最后使用 CommonMark 库将 AST 对象渲染为 HTML 字符串。 你需要将 `example.md` 替换为你自己的 Markdown 文件路径。你还可以根据需要添加更多的配置选项来定制渲染输出。 ### 回答2: Java Markdown模板是一个用于生成Markdown格式文档的Java库。Markdown是一种轻量级标记语言,被广泛用于编写文档、博客和网页等。Java Markdown模板提供了一套简单的API,以便于开发人员在Java程序中生成并格式化Markdown文档。 使用Java Markdown模板,我们可以通过API创建标题、段落、列表、代码块等Markdown元素。我们可以设置元素的样式、字体、字号等属性,还可以为文本添加链接、图片和表格等元素。Java Markdown模板还提供了强大的文本处理功能,可以对文本进行格式化、截取、转化等操作。 Java Markdown模板的优势是在Java环境中操作Markdown文档更加方便。由于编写Markdown文档只需要简单的文本处理,使用Java Markdown模板可以轻松生成复杂的Markdown文档。另外,Java Markdown模板还支持通过模板文件生成Markdown文档,便于批量生成具有相同结构的文档。 总之,Java Markdown模板是一款功能强大、易于使用的Java库,用于生成Markdown格式文档。它提供了丰富的API和文本处理功能,方便开发人员在Java程序中灵活生成和格式化Markdown文档。无论是生成单个文档还是批量生成具有相同结构的文档,Java Markdown模板都是一个非常实用的工具。 ### 回答3: Java Markdown模板是一种用于解析和生成Markdown文档的Java开发工具。Markdown是一种轻量级的标记语言,常用于写作、文档编辑和网页编写。Java Markdown模板提供了一种简单而灵活的方式来处理Markdown文档。 首先,Java Markdown模板通过对Markdown文档进行解析,将其转换为一种数据结构(通常是树状结构),方便后续的处理和操作。它可以解析Markdown的各种标记,如标题、列表、链接、图片等,并提供对这些标记的访问和操作接口。 其次,Java Markdown模板还提供了一套API,可以用于生成Markdown文档。通过API调用,我们可以在Java中编写代码来生成Markdown格式的文本,并指定各种样式、结构和排版。这样,我们就可以利用Java的编程能力和灵活性来生成复杂的Markdown文档。 Java Markdown模板的使用非常简单。我们只需要引入相应的库文件和依赖项,然后在Java代码中创建解析器或生成器实例,就可以开始解析或生成Markdown文档了。解析Markdown文档时,我们可以将其转换为HTML代码(用于展示和网页呈现),或者转换为其他格式,如LaTeX、PDF等(用于打印和发布)。生成Markdown文档时,我们可以根据需求灵活设置各种样式和结构,以满足不同的需求。 总的来说,Java Markdown模板为我们提供了一种方便、灵活的方式来处理和操作Markdown文档。无论是解析还是生成,Java Markdown模板都可以满足我们对Markdown文档的各种需求,使得我们能够更加高效地处理和编辑Markdown文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值