占位符替换
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PlaceHolder {
private static final String HOLDER_START = "${";
private static final String HOLDER_END = "}";
public static void main(String[] args) {
Map<String, String> params = new HashMap<>(2);
params.put("name", "tom");
params.put("date", "2023-03-01");
params.put("url", "http://www.lxl.com");
String str = "hello world,i love you ${name},today is ${date},the url is ${url}";
String replace = replaceHolder(str, params);
System.out.println(replace);
String str1 = "my name is } name,${,ha ha &{;";
System.out.println(check(str)+"----"+check(str1));
}
public static boolean check(String str) {
if (str == null || "".equals(str.trim())) {
return false;
}
int startIndex = str.indexOf(HOLDER_START);
int endIndex = str.indexOf(HOLDER_END, startIndex);
return startIndex > -1 && endIndex > -1;
}
public static String replaceHolder(String str, Map<String, String> replaced) {
if (str == null || "".equals(str.trim())) {
return str;
}
List<String> params = getHolder(str);
for (String param : params) {
if (!replaced.containsKey(param)) {
continue;
}
String holder = format(param);
str = str.replace(holder, replaced.get(param));
}
return str;
}
public static List<String> getHolder(String str) {
List<String> list = new ArrayList<>();
int startIndex;
int endIndex;
while ((startIndex = str.indexOf(HOLDER_START)) > -1 &&
(endIndex = str.indexOf(HOLDER_END, startIndex)) > -1) {
String param = str.substring(startIndex + HOLDER_START.length(), endIndex);
list.add(param);
str = str.substring(endIndex + HOLDER_END.length());
}
return list;
}
private static String format(String placeHolder) {
return HOLDER_START + placeHolder + HOLDER_END;
}
}