说明
占位符
替换成参数值
例如: (“{}好”, “你”) -> “你好”${key}
替换成 key
对应的参数值
例如:
map.put(“谁”, “大家”);
(“${谁}好”, map) -> “大家好”
代码如下
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StrUtils {
private static final Pattern PATTERN = Pattern.compile("\\$\\{(.*?)\\}");
public static String format(String content, Object... params) {
return formatByDelimit(content, "{}", params);
}
public static String formatByDelimit(String content, String delimit, Object... params) {
if (content == null) {
return null;
}
if (delimit == null || delimit.length() < 1) {
return content;
}
StringBuilder sb = new StringBuilder();
int a = 0, b = 0;
for (int n = 0; n < params.length && (b = content.indexOf(delimit, a)) > -1; n++, a = b + delimit.length()) {
sb.append(content, a, b).append(params[n]);
}
if (a < content.length()) {
sb.append(content, a, content.length());
}
return sb.toString();
}
public static String parse(String content, Map<String, String> map) {
if (content == null) {
return null;
}
if (map == null) {
return content;
}
Matcher matcher = PATTERN.matcher(content);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String value = map.get(matcher.group(1));
if (value != null) {
matcher.appendReplacement(sb, value);
}
}
matcher.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String format1 = format("{}爱{}{}, {}上{}升", "我", "北京", "天安门", "天安门", "太阳");
String format2 = format("{}爱{}{}, {}上{}升{}{}", "我", "北京", "天安门", "天安门", "太阳");
String format3 = format("{}爱{}{}, {}上{}升", "我", "北京", "天安门", "天安门", "太阳", "多余", "参数");
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
System.out.println("---------------------------------------");
String msg = "${谁}爱${哪}${什么}, ${什么}上${太阳}升";
HashMap<String, String> kvs = new HashMap<>();
kvs.put("谁", "我");
kvs.put("哪", "北京");
kvs.put("什么", "天安门");
String parse = parse(msg, kvs);
System.out.println(parse);
}
测试方法打印如下
![运行结果...](https://i-blog.csdnimg.cn/blog_migrate/c91eb129f2ddfdddb9c349365775f2bd.png#pic_center)