Precondition

我有一个字符串,如下所示:

代码如下所示:

Map<String, Object> textParameters=new Hashmap<String,String>();
textParameters.put("firstParameter", "Hello World");
StringSubstitutor substitutor = new StringSubstitutor(textParameters);
String replacedText = substitutor.replace(myText)

替换文本为:

The problem

在替换的字符串中,没有提供secondParameter参数,因此出于这个原因,已打印出声明.

What I want to achieve?

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

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

Question

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

推荐答案

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

在您的情况下,如果未设置键,也可以将其保留为空以隐藏占位符.

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 "

Java相关问答推荐

如何使用jooq generator将表名和列名映射为人类可读的?

如何让JFileChooser(DIRECTORIES_ONLY)从FolderName中的空白开始?

现场观看Android Studio中的变化

Hibernate EmptyInterceptor可以工作,但不能拦截器

如何正确创建序列图?

Com.example.service.QuestionService中的构造函数的参数0需要找不到的类型为';com.example.Dao.QuestionDao;的Bean

测试容器无法加载类路径初始化脚本

如何从Keyloak映射Hibernate实体中的用户

无法使用Freemarker从XML中读取重复的标记值

当b是一个字节并且在Java中值为-1时,为什么b>;>;>;1总是等于-1?

AbstractList保证溢出到其他方法

如何使用外部函数从Java中获取C++ struct 的返回值&;内存API

Maven创建带有特定类的Spring Boot jar和普通jar

java构造函数中的冻结操作何时发生?

如何在 WebSphere Application Server 内的托管线程上运行 BatchEE 作业(job)?

对于 Hangman 游戏,索引 0 超出长度 0 的范围

以较小的时间复杂度找到最大值的最小值

在Java中,在Object#equals()调用期间,两个对象是否必须具有相同的hashCode?我们是否需要在 equals() 中比较 hashCode?

Hibernate 6 + 类的属性持久化为字符串

防止屏幕转换后重叠?