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);
    
  • 相关阅读:
    [转] packagelock.json
    前端框架和技术
    typescript
    微信小程序登陆流程
    Introduction to my galaxy engine 4: Test on local light model
    Introduction to my galaxy engine 3: Local light model
    Introduction to my galaxy engine 5: Differed Lighting
    Introduction to my galaxy engine 2: Depth of field
    自己整理的一些国外免费3D模型网站,以后还会陆续添加
    Introduction to my galaxy engine 6: Differed Lighting 2
  • 原文地址:https://www.cnblogs.com/longying2008/p/14333534.html
Copyright © 2011-2022 走看看