四种替换字符串中的变量方式

本文介绍了Java中四种常见的字符串模板替换方法:1) 使用正则表达式;2) Apache Commons Lang3的StrSubstitutor工具类;3) Java内置的MessageFormat类;4) String.format方法。通过实例代码展示了如何进行变量替换,帮助读者理解并选择合适的方法进行字符串模板处理。

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

1.正则表达式

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringTest {
    public static void main(String[] args) {
        Map valuesMap = new HashMap();
        valuesMap.put("animal", "the fox");
        valuesMap.put("target", "lazy dog");
        String templateString = "The ${animal} jumped over the ${target}. ";
        String middleResult = processTemplate(templateString, valuesMap);
        System.out.println(middleResult);
    }
    public static String processTemplate(String template, Map<String, Object> params){
        StringBuffer sb = new StringBuffer();
        Matcher m = Pattern.compile("\\$\\{\\w+\\}").matcher(template);
        while (m.find()) {
            String param = m.group();
            Object value = params.get(param.substring(2, param.length() - 1));
            m.appendReplacement(sb, value==null ? "" : value.toString());
        }
        m.appendTail(sb);
        return sb.toString();
    }
}

2.工具类替换


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

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

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.4</version>

</dependency>

3. java.text.MessageFormat

Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);

4.java.lang.String

String s = String.format("My name is %s. I am %d.", "Andy", 18);

参考文章:

Apache StrSubstitutor使用方法_Mischeung的博客-优快云博客

Java 模板变量替换——字符串替换器_Andy's Blog-优快云博客_java 字符串变量替换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值