Java中是否有String替换机制,在该机制中,我可以用文本传递对象,并在字符串出现时替换它。
例如,文本为:
你好${user.name},
欢迎使用${site.name}。
我拥有的对象是“用户”和“站点”。我想用对象中的等价值替换${}中给出的字符串。这与替换速度模板中的对象相同
使用Apache Commons文本中的StringSubstitutor
https://commons.apache.org/proper/commons-text/
它会为你做的(和它的开源…)
地图<;字符串,字符串>;valuesMap=新哈希映射<;字符串,字符串>;();
价值Map.put(“动物”、“快速棕色狐狸”);
价值映射放置(“目标”、“懒狗”);
String templateString=“该${animal}跳过了${target}。”;
StringSubstitutor sub=新StringSubstitutor(值Map);
String resolvedString=sub.replace(templateString);