StrSubstitutes的使用

StrSubstitutes文档分析:

原文档地址:https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html

作用:

用值替换字符串中的变量,这个类接受一段文本并替换其中的所有变量
默认结构:${variableName}, 前缀 ${ 和后缀 } 可以通过构造方法或set方法更改

递归替换:${jre-${java.specification.version}}
需要设置 setEnableSubstitutionInVariables 为 true.

 	@Test
    public void strSubstitutorTest(){
        String str = "str: ${variableName}";
        String str2 = "str2: #{variableName2}";
        String str3 = "str3: ${variableName3-${variableName4}}";
        String str4 = "str4: system properties: os name: ${os.name}, java version: ${java.version}";

        Map<String, Object> stringObjectMap = new HashMap<>(16);
        stringObjectMap.put("variableName", "value1");
        stringObjectMap.put("variableName2", "value2");
        stringObjectMap.put("variableName3-value4", "value3");
        stringObjectMap.put("variableName4", "value4");

        // 修改前缀和后缀 -- 构造方法
        StrSubstitutor strSubstitutor = new StrSubstitutor(stringObjectMap, "#{", "}");
        String replace = strSubstitutor.replace(str2);
        System.out.println(replace);

        // 修改前缀和后缀 -- set方法
        StrSubstitutor strSubstitutor1 = new StrSubstitutor(stringObjectMap);
        strSubstitutor1.setVariablePrefix("#{");
        String replace1 = strSubstitutor1.replace(str2);
        System.out.println(replace1);

        // 使用静态方法替换
        String replace2 = StrSubstitutor.replace(str, stringObjectMap);
        System.out.println(replace2);

        // 递归替换
        StrSubstitutor strSubstitutor3 = new StrSubstitutor(stringObjectMap);
        strSubstitutor3.setEnableSubstitutionInVariables(true);
        String replace3 = strSubstitutor3.replace(str3);
        System.out.println(replace3);

        // 系统值替换
        String replace4 = StrSubstitutor.replaceSystemProperties(str4);
        System.out.println(replace4);
    }

如果文本中需要有这种格式:The variable ${${name}} must be used.
可以使用不同的前缀和后缀避免冲突,或者使用 $ 转义:The variable $${${name}} must be used.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值