1.封装替换符工具类
public static String replacePlaceholders(String value, final Properties properties) {
// 可选占位符
final Pattern optionalPattern = Pattern.compile("@\\[(.*?)\\]");
// 必选占位符
final Pattern requiredPattern = Pattern.compile("\\$\\{param\\.([^}]+)\\}");
// 处理可选占位符
Matcher optionalMatcher = optionalPattern.matcher(value.toString());
StringBuffer optionalMatchResult = new StringBuffer();
while (optionalMatcher.find()) {
String optionalContent = optionalMatcher.group(1);
Matcher innerRequiredMatcher = requiredPattern.matcher(optionalContent);
boolean containsEmptyRequired = false;
while (innerRequiredMatcher.find()) {
String key = innerRequiredMatcher.group(1);
String replacement = properties.getProperty(key);
if (replacement == null || replacement.isEmpty()) {
containsEmptyRequired = true;
break;
}
}
if (containsEmptyRequired) {
optionalMatcher.appendReplacement(optionalMatchResult, "");
} else {
optionalMatcher.appendReplacement(optionalMatchResult, Matcher.quoteReplacement(optionalContent));
}
}
optionalMatcher.appendTail(optionalMatchResult);
// 处理必选占位符
Matcher requiredMatcher = requiredPattern.matcher(optionalMatchResult);
StringBuffer requiredMatchResult = new StringBuffer();
while (requiredMatcher.find()) {
String key = requiredMatcher.group(1);
String replacement = properties.getProperty(key);
if (replacement == null) {
throw new IllegalArgumentException("Required placeholder ${" + key + "} not found in properties");
}
requiredMatcher.appendReplacement(requiredMatchResult, Matcher.quoteReplacement(replacement));
}
requiredMatcher.appendTail(requiredMatchResult);
// 返回最终结果
return requiredMatchResult.toString();
}
2.样例调用
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("year", "\"2023\"");
properties.setProperty("unitIndustry", "[\"国企\", \"民企\"]");
String template = "SELECT * from xxx where budget_year = ${param.year} @[and unit_industry_name in ${param.unitIndustry}] @[and unit_industry_name1 in ${param.unitIndustry1}]";
try {
String result = DacpPlaceholderReplacer.replacePlaceholders(template, properties);
System.out.println(result);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
3.运行结果