String replacement in java, similar to a velocity template

前端 未结 8 1373
小鲜肉
小鲜肉 2020-11-28 04:59

Is there any String replacement mechanism in Java, where I can pass objects with a text, and it replaces the string as it occurs.
For example, the text is :

8条回答
  •  囚心锁ツ
    2020-11-28 05:25

    Use StringSubstitutor from Apache Commons Text.

    https://commons.apache.org/proper/commons-text/

    It will do it for you (and its open source...)

     Map valuesMap = new HashMap();
     valuesMap.put("animal", "quick brown fox");
     valuesMap.put("target", "lazy dog");
     String templateString = "The ${animal} jumped over the ${target}.";
     StringSubstitutor sub = new StringSubstitutor(valuesMap);
     String resolvedString = sub.replace(templateString);
    

提交回复
热议问题