参考:java模板字符串解析(占位符解析)
【最常用】两种java中的占位符的使用
Java中强大的format
java模板替换_java替换字符串模板(模板渲染)

第一种:使用%s占位,使用String.format转换

  1. public class Test {
  2. public static void main(String[] args) {
  3. String url = "我叫%s,今年%s岁。";
  4. String name = "小明";
  5. String age = "28";
  6. url = String.format(url,name,age);
  7. System.out.println(url);
  8. }
  9. }

第二种:使用{1}占位,使用MessageFormat.format转换

  1. public class Test {
  2. public static void main(String[] args) {
  3. String url02 = "我叫{0},今年{1}岁。";
  4. String name = "小明";
  5. String age = "28";
  6. url02 = MessageFormat.format(url02,name,age);
  7. System.out.println(url02);
  8. }
  9. }

第三种:自定义模版字符串解析

  1. @Test
  2. public void test() {
  3. String aa = "我们都是好孩子,${name1}说是嘛: 我觉得${name2}是大聪明!";
  4. Map<String, String> map = MapUtils.newHashMap();
  5. map.put("name1", "小花");
  6. map.put("name2", "小明");
  7. // 输出:我们都是好孩子,小花说是嘛: 我觉得小明是大聪明!
  8. log.info(TjStringUtils.templateString(aa, map));
  9. }
  1. package com.tj.demo.utils;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.Map;
  4. @Slf4j
  5. public abstract class TjStringUtils {
  6. /**
  7. * 前站位符号: "${"
  8. */
  9. public static final String PLACEHOLDER_PREFIX = "${";
  10. /**
  11. * 后站位符: "}"
  12. */
  13. public static final String PLACEHOLDER_SUFFIX = "}";
  14. /**
  15. * JAVA模版字符串
  16. *
  17. * @param template 模版,里面的需要替换的部分使用${变量名}站位
  18. * @param parameter map集合,里面是变量名和值
  19. * @return
  20. */
  21. public static String templateString(String template, Map<String, String> parameter) {
  22. if (parameter == null || parameter.isEmpty()) {
  23. return template;
  24. }
  25. StringBuffer buf = new StringBuffer(template);
  26. int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);
  27. while (startIndex != -1) {
  28. int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length());
  29. if (endIndex != -1) {
  30. String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
  31. int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();
  32. try {
  33. String propVal = parameter.get(placeholder);
  34. if (propVal != null) {
  35. buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
  36. nextIndex = startIndex + propVal.length();
  37. } else {
  38. log.info("无法解析占位符'" + placeholder + "' in [" + template + "] ");
  39. }
  40. } catch (Exception ex) {
  41. log.info("无法解析占位符'" + placeholder + "' in [" + template + "]: " + ex);
  42. }
  43. startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);
  44. } else {
  45. startIndex = -1;
  46. }
  47. }
  48. return buf.toString();
  49. }
  50. }