当前位置:   article > 正文

java占位符替换五种方式_java ppt占位符替换

java ppt占位符替换

简介

在业务开发中,经常需要输出文本串。其中,部分场景下大部分文本内容是一样的,只有少部分点是不一样。简单做法是直接拼接字段,但是这会有个问题。后面如果想要修改内容,那么每个地方都要修改,这不符合设计模式中的开闭原则,面向应该对扩展开放,对修改关闭。

如何解决这个问题? 先来看现实生活中的例子,个人信息填写。一般会要填写表格,已经定义好了姓名,性别,年龄等字段,只要填写对应的个人信息就好了。在程序开发中,我们会预先定义好一个字符串模板,需要改动的点使用占位符。在使用中,使用具体的内容替换掉占位符,就能生成我们所需要的文本内容。

本文总结了占位符替换五种方法。前三种方法占位符格式支持自定义。本文使用${param!}的格式,前三种方法示例模板为:

String TEMPLATE = "姓名:${name!},年龄:${age!},手机号:${phone!}";

待填充参数为:

  1. private static final Map<String, String> ARGS = new HashMap<String, String>() {{
  2.         put("name""张三");
  3.         put("phone""10086");
  4.         put("age""21");
  5.     }};

StringUtils.replace

StringUtils.replace方法定义:

String replace(String textString searchString, String replacement);

StringUtils.replace能够将入参中的searchString字符串替换成replacement字符串。在使用时,参数名称补充上占位符标记。

示例:

  1. String remark = TEMPLATE;
  2. for (Map.Entry<StringString> entry : ARGS.entrySet()) {
  3.     remark = StringUtils.replace(remark, "${" + entry.getKey() + "!}", entry.getValue());
  4. }
  5. System.out.println(remark);

正则表达式Matcher

使用正则表达式依次找到占位符的位置,使用实际参数替换掉占位符。

示例:

  1. Pattern TEMPLATE_ARG_PATTERN = Pattern.compile("\\$\\{(.+?)!}"); // ${param!}
  2. Matcher m = TEMPLATE_ARG_PATTERN.matcher(TEMPLATE);
  3. StringBuffer sb = new StringBuffer();
  4. while (m.find()) {
  5.     String arg = m.group(1);
  6.     String replaceStr = ARGS.get(arg);
  7.     m.appendReplacement(sb, replaceStr != null ? replaceStr : "");
  8. }
  9. m.appendTail(sb);
  10. System.out.println(sb.toString());

StringSubstitutor

StringSubstitutor功能比较多,使用起来比较灵活。支持默认占位符${param}, 当然也可以自定义前缀和后缀,甚至支持默认值。

  1. public <V> StringSubstitutor(Map<String, V> valueMap);
  2. public <V> StringSubstitutor(Map<String, V> valueMap, String prefix, String suffix);

示例:

  1. StringSubstitutor sub = new StringSubstitutor(ARGS,"${","!}");
  2. System.out.println(sub.replace(TEMPLATE));

MessageFormat.format

Java的自带类MessageFormat支持做占位符替换,占位符格式为{index}, index是索引号。

  1. String template = "Hello, my home is {0} and I am {1} years old.";
  2. Object[] replageArgs ={"Alice",25};
  3. String message = MessageFormat.format(template, replageArgs);

String.format

String.format同样可以实现占位符替换。

  1. String template = "Hello, my name is %s and I am %d years old.";
  2. Object[] replageArgs ={"Alice",25};
  3. String message = String.format(template, replageArgs);
  4. System.out.println(message); // 输出:Hello, my name is Alice and I am 25 years old.

总结

本文总结了占位符替换的五种方法。MessageFormat.format和String.format java自带功能,无需引入外部jar包,能够完成基本的替换功能。StringUtils.replace, 正则表达式,StringSubstitutor支持自定义占位符格式,能够完成更复杂的功能。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/819490
推荐阅读
相关标签
  

闽ICP备14008679号