首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Apache StringSubstitutor -用空字符串替换不匹配的变量

Apache StringSubstitutor -用空字符串替换不匹配的变量
EN

Stack Overflow用户
提问于 2022-05-27 09:33:21
回答 2查看 1.3K关注 0票数 2

先决条件

我有一个字符串,看起来如下:String myText= "This is a foo text containing ${firstParameter} and ${secondParameter}"

代码是这样的:

代码语言:javascript
运行
复制
Map<String, Object> textParameters=new Hashmap<String,String>();
textParameters.put("firstParameter", "Hello World");
StringSubstitutor substitutor = new StringSubstitutor(textParameters);
String replacedText = substitutor.replace(myText)

replacedText将是:This is a foo text containing Hello World and ${secondParameter}

问题

在替换的字符串中,没有提供secondParameter参数,因此为此打印了声明。

我想实现什么?

如果一个参数没有映射,那么我想用一个空字符串替换它的声明。

在这个示例中,我想实现以下目标:This is a foo text containing Hello World and

问题

如何使用StringUtils/Stringbuilder实现上述结果?我应该用regex代替吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-27 09:54:34

您可以通过向占位符添加一个默认值来实现这一点。(例如${secondParameter:-my default value})。

在这种情况下,如果没有设置键,也可以将其保留为空以隐藏占位符。

代码语言:javascript
运行
复制
String myText = "This is a foo text containing ${firstParameter} and ${secondParameter:-}";
Map<String, Object> textParameters = new HashMap<>();
textParameters.put("firstParameter", "Hello World");
StringSubstitutor substitutor = new StringSubstitutor(textParameters);
String replacedText = substitutor.replace(myText);
System.out.println(replacedText);
// Prints "This is a foo text containing Hello World and "
票数 2
EN

Stack Overflow用户

发布于 2022-05-28 16:11:07

如果要为所有变量设置默认值,可以构造StringSubstitutor with StringLookup,其中StringLookup只是包装参数映射并使用getOrDefault提供默认值。

代码语言:javascript
运行
复制
import org.apache.commons.text.StringSubstitutor;
import org.apache.commons.text.lookup.StringLookup;

import java.util.HashMap;
import java.util.Map;

public class SubstituteWithDefault {
    public static void main(String[] args) {
        String myText = "This is a foo text containing ${firstParameter} and ${secondParameter}";
        Map<String, Object> textParameters = new HashMap<>();
        textParameters.put("firstParameter", "Hello World");
        StringSubstitutor substitutor = new StringSubstitutor(new StringLookup() {
            @Override
            public String lookup(String s) {
                return textParameters.getOrDefault(s, "").toString();
            }
        });
        String replacedText = substitutor.replace(myText);
        System.out.println(replacedText);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72403340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档