Apache StrSubstitutor使用方法

Java中,对于格式化字符串,不管是String.format,仍是MessageFormat,都很难用。Velocity却是不错,可就是过重。今天给你们推荐Apache commons-lang中的StrSubstitutor。html

文档地址:https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/StrSubstitutor.htmljava

StrSubstitutor在apache的commons-lang3包中,要使用,请在pom.xml里加入以下依赖:apache

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

一、直接替换系统属性值api

StrSubstitutor.replaceSystemProperties(
    "You are running with java.version = ${java.version} and os.name = ${os.name}.");

二、使用Map替换字符串中的占位符ui

Map valuesMap = HashMap();
valuesMap.put(
"animal", "quick brown fox");
valuesMap.put(
"target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub
= new StrSubstitutor(valuesMap); String resolvedString = sub.replace(templateString);

resolvedString的结果:The quick brown fox jumped over the lazy dog.spa

三、StrSubstitutor会递归地替换变量,好比:code

Map<String, Object> params = Maps.newHashMap();
params.put("name", "${x}");
params.put("x", "y");
StrSubstitutor strSubstitutor
= new StrSubstitutor(params);

String hello2 = "${name}";
System.out.println(strSubstitutor.replace(hello2));

最后会输出:yorm

四、有时变量内还嵌套其它变量,这个StrSubstitutor也是支持的,不过要调用下setEnableSubstitutionInVariables才能够。xml

Map<String, Object> params = Maps.newHashMap();
params.put("jre-1.8", "java-version-1.8");
params.put("java.specification.version", "1.8");
StrSubstitutor strSubstitutor = new StrSubstitutor(params);
           
strSubstitutor.setEnableSubstitutionInVariables(true);
System.out.println(strSubstitutor.replace("${jre-${java.specification.version}}"));

输出:java-version-1.8htm

相关文章
相关标签/搜索