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);
    
  • 相关阅读:
    Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    [bzoj4720] [noip2016]换教室
    [noip2017]时间复杂度
    2018-8-14队测
    2018-8-13队测
    [bzoj4555] [Tjoi2016&Heoi2016]求和
    oracle安装—Windows7旗舰版32位安装oracle10g方法
    有一种书叫——迫不及待
    iptable防火墙配置
    kickstrat
  • 原文地址:https://www.cnblogs.com/longying2008/p/14333534.html
Copyright © 2011-2022 走看看