先决条件
我有一个字符串,看起来如下: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)
replacedText将是:This is a foo text containing Hello World and ${secondParameter}
问题
在替换的字符串中,没有提供secondParameter
参数,因此为此打印了声明。
我想实现什么?
如果一个参数没有映射,那么我想用一个空字符串替换它的声明。
在这个示例中,我想实现以下目标:This is a foo text containing Hello World and
问题
如何使用StringUtils/Stringbuilder实现上述结果?我应该用regex代替吗?
发布于 2022-05-27 09:54:34
您可以通过向占位符添加一个默认值来实现这一点。(例如${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 "
发布于 2022-05-28 16:11:07
如果要为所有变量设置默认值,可以构造StringSubstitutor
with StringLookup
,其中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);
}
}
https://stackoverflow.com/questions/72403340
复制相似问题