0%

java字符串替换

依赖

Apache StrSubstitutor使用占位符.

 <dependency>
    <groupId>org.apache.commons</groupId>
     <artifactId>commons-lang3</artifactId>
     <version>3.4</version>
 </dependency>

使用

  • 直接获取系统属性
System.out.println(StrSubstitutor.replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}."));
  • 使用map
Map<String, String> params = new HashMap<>();
params.put("name", "happywzy");
params.put("age", "15");
String temp = "你好,${name}! 你今年${age}岁啦!";
System.out.println(StrSubstitutor.replace(temp, params));
  • 递归替换变量
Map<String, Object> params = new HashMap<>();
params.put("name", "${x}");
params.put("x", "happywzy");
StrSubstitutor strSubstitutor = new StrSubstitutor(params);
String name = "${name}";
System.out.println(strSubstitutor.replace(name));
  • 嵌套替换变量
Map<String, Object> params = new HashMap<>();
params.put("jre-1.8", "java-version-1.8");
params.put("java.specification.version", "1.8");
StrSubstitutor strSubstitutor = new StrSubstitutor(params);
strSubstitutor.setEnableSubstitutionInVariables(true);
System.out.println(strSubstitutor.replace("${jre-${java.specification.version}}"));