前言:
Java中,对于格式化字符串,不论是format,还是MessageFormat,都有点复杂,用起来也比较费劲。Velocity倒是还行,可就是太重。这里说下Apache commons-lang中的StrSubstitutor。
正文:
1.引入maven依赖包
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency>
2.用法-替换系统内的变量值
String str=StrSubstitutor.replaceSystemProperties( "You are running with java.version = ${java.version} and os.name = ${os.name}."); System.out.println(str);
输出结果:You are running with java.version = 1.8.0_161 and os.name = Windows 7
3.用法-使用map的占位符进行替换
Map valuesMap = HashMap(); valuesMap.put("name", "小红"); valuesMap.put("sex", "女"); String templateString = "很高兴来到IT讲坛,我的名字是${name},性别: ${sex}。"; StrSubstitutor sub = new StrSubstitutor(valuesMap); String resolvedString = sub.replace(templateString);
输出结果:
很高兴来到IT讲坛,我的名字是${小红},性别: ${女}。
4.用法-递归替换value
Map<String, Object> params = Maps.newHashMap(); params.put("name", "${x}"); params.put("x", "小红"); StrSubstitutor strSubstitutor = new StrSubstitutor(params); String hello2 = "${name}"; System.out.println(strSubstitutor.replace(hello2));
输出结果:
小红