Apache commons StringSubstitutor 替换占位符

博客指出Java中String.format和MessageFormat格式化字符串难用,Velocity太重,推荐使用Apache commons - lang中的StrSubstitutor。介绍了其在commons - lang3包中的使用依赖,还列举了直接替换系统属性值、用Map替换占位符、递归替换变量等使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java中,对于格式化字符串,不论是String.format,还是MessageFormat,都很难用。Velocity倒是不错,可就是太重。今天给大家推荐Apache commons-lang中的StrSubstitutor。

文档地址:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/StrSubstitutor.html

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

 <dependency>
    <groupId>org.apache.commons</groupId>
     <artifactId>commons-lang3</artifactId>
     <version>3.4</version>
 </dependency>

1、直接替换系统属性值

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

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

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.

3、StrSubstitutor会递归地替换变量,比如:

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));

最后会输出:y

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

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.8

 


来源于:

https://blog.youkuaiyun.com/mischeung/article/details/79753903

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值