package com.wenxiaowu.string;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* 配置文件或模板中的占位符替换工具类
*/
public class PlaceholderTest {
@Test
public void test() {
String aa= "我们都是好孩子,${name1}说是嘛: 我觉得${name2}是大聪明!";
Map<String, String> map = new HashMap<>();
map.put("name1","小花");
map.put("name2","小明");
// 输出:我们都是好孩子,小花说是嘛: 我觉得小明是大聪明!
System.out.println(PlaceholderTest.resolvePlaceholders(aa, map));
}
/**
* Prefix for system property placeholders: "${"
*/
public static final String PLACEHOLDER_PREFIX = "${";
/**
* Suffix for system property placeholders: "}"
*/
public static final String PLACEHOLDER_SUFFIX = "}";
public static String resolvePlaceholders(String text, Map<String, String> parameter) {
if (parameter == null || parameter.isEmpty()) {
return text;
}
StringBuffer buf = new StringBuffer(text);
int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);
while (startIndex != -1) {
int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length());
if (endIndex != -1) {
String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
try {
String propVal = parameter.get(placeholder);
if (propVal != null) {
buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
nextIndex = startIndex + propVal.length();
} else {
System.out.println("Could not resolve placeholder '" + placeholder + "' in [" + text + "] ");
}
} catch (Exception ex) {
System.out.println("Could not resolve placeholder '" + placeholder + "' in [" + text + "]: " + ex);
}
startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);
} else {
startIndex = -1;
}
}
return buf.toString();
}
}
java模板字符串解析(占位符解析)
最新推荐文章于 2024-07-26 02:59:06 发布