mirror of
https://github.com/tiennm99/zfoo.git
synced 2026-10-11 03:13:51 +00:00
feat: render placeholder in string template like JavaScript
This commit is contained in:
1 parent
da315a1818
commit
24b5b6012a
1 file changed
+18
@@ -16,6 +16,7 @@ import com.zfoo.protocol.collection.ArrayUtils;
|
||||
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -468,6 +469,23 @@ public abstract class StringUtils {
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化字符串,类似JavaScript的占位符${name}替换
|
||||
*/
|
||||
public static String render(String template, Map<String, String> params) {
|
||||
var pattern = Pattern.compile("\\$\\{(\\w+)\\}");
|
||||
var matcher = pattern.matcher(template);
|
||||
var sb = new StringBuffer();
|
||||
|
||||
while (matcher.find()) {
|
||||
var key = matcher.group(1);
|
||||
var replacement = params.getOrDefault(key, "");
|
||||
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static boolean isEnglishChar(char ch) {
|
||||
return ENGLISH_SET.contains(ch);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user