zoukankan      html  css  js  c++  java
  • 模板字符串解析

    使用Hutool解析模板字符串

    要求:使用 {varName} 占位
    评价:如果paramMap中含有大量无用键值时不推荐使用这种方式

    1. 引入依赖:
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.4.1</version>
    </dependency>
    
    1. 代码示例:
    String template = "My name is {name}, I'm {age} years old. How old are you?";
    Map<String, Object> paramMap = Maps.newHashMap();
    paramMap.put("name", "林曦");
    paramMap.put("age", 30);
    String result = StrUtil.format(template, paramMap);
    System.out.println("== Hutool处理结果 ==");
    System.out.println(result);
    

    使用commons-text解析模板字符串

    要求:使用 ${varName} 占位

    1. 引入依赖:
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>1.9</version>
    </dependency>
    
    1. 代码示例:
    String template = "My name is ${name}, I'm ${age} years old. How old are you?";
    Map<String, Object> paramMap = Maps.newHashMap();
    paramMap.put("name", "林曦");
    paramMap.put("age", 30);
    StringSubstitutor stringSubstitutor = new StringSubstitutor(paramMap);
    String result = stringSubstitutor.replace(template);
    System.out.println("== commons-text处理结果 ==");
    System.out.println(result);
    

    使用自定义方法解析模板字符串

    要求:使用 ${varName} 占位

    1. 自定义解析方法
    public static String format(String template, Map<String, Object> paramMap) {
        Matcher matcher = Pattern.compile("\$\{\w+\}").matcher(template);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String group = matcher.group();
            String paramKey = group.substring(2, group.length() - 1);
            Object value = paramMap.get(paramKey);
            matcher.appendReplacement(sb, Objects.isNull(value) ? "" : value.toString());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    
    1. 代码示例:
    String template = "My name is ${name}, I'm ${age} years old. How old are you?";
    Map<String, Object> paramMap = Maps.newHashMap();
    paramMap.put("name", "林曦");
    paramMap.put("age", 30);
    String result = format(template, paramMap);
    System.out.println("== 自定义format方法处理结果 ==");
    System.out.println(result);
    
  • 相关阅读:
    中国首届React开发者大会 8月18日 广州举行
    事件循环:Flutter 中代码是如何执行和运行的
    大前端趋势所向:这么多跨端技术,为什么选择 Flutter?
    通往大前端的一把关键钥匙 Flutter
    如何选一部好的手机?性价比高的智能手机推荐,2020智能手机排行榜!
    智能手机边充电边玩对电池有什么损害吗?
    你的智能手机究竟能用多久?
    新型添加技术
    智能手机
    姐姐不愧是姐姐,快看《乘风破浪的姐姐》
  • 原文地址:https://www.cnblogs.com/longying2008/p/14333534.html
Copyright © 2011-2022 走看看