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.