Java 中,对于格式化字符串,不论是 String.format,还是 MessageFormat,都很难用。Velocity 倒是不错,可就是太重。今天给大家推荐 Apache commons-lang 中的 StrSubstitutor。
文档地址:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/StrSubstitutor.html

StrSubstitutor 在 apache 的 commons-lang3 包中,要使用,请在 pom.xml 里加入如下依赖:

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-lang3</artifactId>
  4. <version>3.4</version>
  5. </dependency>

1、直接替换系统属性值

  1. StrSubstitutor.replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}.");

2、使用 Map 替换字符串中的占位符

  1. Map valuesMap = HashMap();
  2. valuesMap.put("animal", "quick brown fox");
  3. valuesMap.put("target", "lazy dog");
  4. String templateString = "The ${animal} jumped over the ${target}.";
  5. StrSubstitutor sub = new StrSubstitutor(valuesMap);
  6. String resolvedString = sub.replace(templateString);

resolvedString的结果:The quick brown fox jumped over the lazy dog.

3、StrSubstitutor会递归地替换变量,比如:

  1. Map<String, Object> params = Maps.newHashMap();
  2. params.put("name", "${x}");
  3. params.put("x", "y");
  4. StrSubstitutor strSubstitutor = new StrSubstitutor(params);
  5. String hello2 = "${name}";
  6. System.out.println(strSubstitutor.replace(hello2));

最后会输出:y

4、有时变量内还嵌套其它变量,这个StrSubstitutor也是支持的,不过要调用下setEnableSubstitutionInVariables才可以。

  1. Map<String, Object> params = Maps.newHashMap();
  2. params.put("jre-1.8", "java-version-1.8");
  3. params.put("java.specification.version", "1.8");
  4. StrSubstitutor strSubstitutor = new StrSubstitutor(params);
  5. strSubstitutor.setEnableSubstitutionInVariables(true);
  6. System.out.println(strSubstitutor.replace("${jre-${java.specification.version}}"));

https://blog.csdn.net/weixin_41888813/article/details/90481607