• 模板字符串解析


    使用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);
    
  • 相关阅读:
    Hadoop生态圈-Hive快速入门篇之HQL的基础语法
    Hadoop生态圈-Hive快速入门篇之Hive环境搭建
    Hadoop生态圈-zookeeper的API用法详解
    Hadoop生态圈-zookeeper完全分布式部署
    Hadoop基础-MapReduce的工作原理第一弹
    Hadoop基础-HDFS的读取与写入过程
    java基础-回调函数(callback)
    Hadoop基础-网络拓扑机架感知及其实现
    Hadoop基础-HDFS数据清理过程之校验过程代码分析
    Hadoop基础-Protocol Buffers串行化与反串行化
  • 原文地址:https://www.cnblogs.com/longying2008/p/14333534.html
Copyright © 2020-2023  润新知