0%

使用commons-text 进行占位符替换

背景描述

日常开发工作中会遇到替换占位符的需求

例如给用户发验证码短信时需要拼接如下的字符串 “张三 欢迎使用,您的验证码是123456” , 其中用户名和验证码需要动态拼接,其他字符串都是固定的. 则这种情况下可以考虑使用commons-text,比自己实现字符串替换要好.

具体步骤

引入 commons-text 的依赖

1
2
3
4
5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void test1(){
/*
* 演示最简单的使用方式
* 这里默认的替换符就是${}
* */
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "admin");
params.put("captcha", "123456");
StringSubstitutor stringSubstitutor=new StringSubstitutor(params);
String template = "${userName} 欢迎使用,您的验证码是${captcha}";
String result=stringSubstitutor.replace(template);
System.out.println(result);
}