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



前提条件

我有一根绳子,看起来像这样:String myText= "This is a foo text containing ${firstParameter} and ${secondParameter}"

代码看起来是这样的:

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

替换的文本将是:This is a foo text containing Hello World and ${secondParameter}

问题

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

我想要实现什么

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

在我想要实现的示例中:This is a foo text containing Hello World and

问题

如何使用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 "

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


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

相关内容

最新更新