替换字符串中 ${} 标识的变量;记录一下以备不时之需
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyJavaTest {
@Test
public void compare() {
Map properties = new HashMap<>();
properties.put("name", "法外狂徒张三");
String template = "${relevant.$.departments}:网络不是法外之地,${name}一定会被严惩";
System.out.println(replaceVariable(template, properties)); // :网络不是法外之地,法外狂徒张三一定会被严惩
}
public static String replaceVariable(String template, Map properties) {
StringBuffer sb = new StringBuffer();
// 该表达式匹配${中的数字字母下划线,英文点和$
Matcher matcher = Pattern.compile("\$\{[\.\$\w]+}").matcher(template);
while (matcher.find()) {
String param = matcher.group();
String varible = param.substring(2, param.length() - 1);
// 追加并替换变量
Object value = properties.get(varible);
matcher.appendReplacement(sb, value == null ? "" : String.valueOf(value));
}
// 复制输入序列的其余部分
matcher.appendTail(sb);
return sb.toString();
}
}



