Apache commons-lang3包中的 StrSubstitutor可以將字符串中的變量替換為指定的值
從commons-lang3-3.6.jar版本起 org.apache.commons.lang3.text.StrSubstitutor已經(jīng)過時,文檔上建議用commons-text的org.apache.commons.text.StrSubstitutor代替。
先引入
commons-text-1.2.jar
寫個簡單的方法測試一下
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.text.StrSubstitutor;
/**
* 占位符替換
*
*/
public class Placeholder {
/**
* 替換
* @param source 源內(nèi)容
* @param parameter 占位符參數(shù)
* @param prefix 占位符前綴 例如:${
* @param suffix 占位符后綴 例如:}
* @param enableSubstitutionInVariables 是否在變量名稱中進(jìn)行替換 例如:${system-${版本}}
*
* 轉(zhuǎn)義符默認(rèn)為'$'怕磨。如果這個字符放在一個變量引用之前紧索,這個引用將被忽略竞滓,不會被替換 如$${a}將直接輸出${a}
* @return
*/
public static String replace(String source,Map<String, Object> parameter,String prefix, String suffix,boolean enableSubstitutionInVariables){
//StrSubstitutor不是線程安全的類
StrSubstitutor strSubstitutor = new StrSubstitutor(parameter,prefix, suffix);
//是否在變量名稱中進(jìn)行替換
strSubstitutor.setEnableSubstitutionInVariables(enableSubstitutionInVariables);
return strSubstitutor.replace(source);
}
/**
* 測試
*/
public static void test(){
//替換字符串中的占位符
Map<String, Object> params = new HashMap<String, Object>();
params.put("user", "admin");
params.put("password", "123456");
params.put("system-version", "windows 10");
params.put("版本", "version");//中文也可以
params.put("詳", "翔");//中文也可以
System.out.println(replace("你的用戶名是${user},密碼是${password}坯沪。系統(tǒng)版本${system-${版本}}",params,"${","}",true));
System.out.println(replace("表達(dá)對一個人無比的崇拜怎么表述最好?答:“愿聞其${詳}”",params,"${","}",false));
}
}
運(yùn)行結(jié)果
你的用戶名是admin,密碼是123456政恍。系統(tǒng)版本windows 10