依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
使用
默认占位符为${}
替换环境变量
System.out.println(StrSubstitutor.replaceSystemProperties("my os name is ${os.name}, my java version is ${java.version}"));
// my os name is Windows 8.1, my java version is 1.8.0_31
System.setProperty("Test","xxx-yyy"); System.out.println(StrSubstitutor.replaceSystemProperties("the property Test value is ${Test}"));
// the property Test value is xxx-yyy
替换Map
Map<String,Object> map = new HashMap<>();
map.put("userName","Nothing");
map.put("age",18);
System.out.println(StrSubstitutor.replace("my name is ${userName} and age is ${age}", map));
// my name is Nothing and age is 18
递归替换变量
Map<String,Object> map = new HashMap<>();
map.put("userName","${X}");
map.put("X","hahaha");
map.put("age",100);
System.out.println(StrSubstitutor.replace("my name is ${userName} and age is ${age}", map));
// my name is hahaha and age is 100
自定义占位符
Map<String,Object> map = new HashMap<>();
map.put("userName","iii");
map.put("age",66);
System.out.println(StrSubstitutor.replace("my name is [userName] and age is [age]", map,"[","]"));
// my name is iii and age is 66