public class Tools {
private static Pattern pattern;
static {
pattern = Pattern.compile("((?<=\\{)([a-zA-Z_]{1,})(?=\\}))");
}
/**
* 字符串替换, 将 {} 中的内容, 用给定的参数进行替换
*
* @param text
* @param params
* @return
*/
public static String format(String text, Map<String, Object> params) {
// 把文本中的所有需要替换的变量捞出来, 丢进keys
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String key = matcher.group();
text = StringUtils.replace(text, "{" + key + "}", params.get(key) + "");
}
return text;
}
public static String replace(String text, Object ... args) {
return MessageFormat.format(text, args);
}
public static String replaceFormat(String text, Map<String, Object> map) {
List<String> keys = new ArrayList<>();
// 把文本中的所有需要替换的变量捞出来, 丢进keys
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String key = matcher.group();
if (!keys.contains(key)) {
keys.add(key);
}
}
// 开始替换, 将变量替换成数字, 并从map中将对应的值丢入 params 数组
Object[] params = new Object[keys.size()];
for (int i = 0; i < keys.size(); i++) {
text = text.replaceAll(keys.get(i), i + "");
params[i] = map.get(keys.get(i));
}
return replace(text, params);
}
//测试
public static void main(String[] args) {
String text = "hello {user}, welcome to {place}! now timestamp is: {time} !";
Map<String, Object> map = new HashMap<>(2);
map.put("time", System.currentTimeMillis());
map.put("place", "China");
map.put("user", "Lucy");
String res = replaceFormat(text, map);
System.out.println(res); // 输出 : hello Lucy, welcome to China! now 2stamp is: 1,490,619,291,742 !
}
}
字符串替换工具类
最新推荐文章于 2025-06-02 09:51:12 发布
574

被折叠的 条评论
为什么被折叠?



