【发布时间】:2012-12-26 18:38:55
【问题描述】:
目前我正在使用org.apache.commons.lang.text.StrSubstitutor 做:
Map m = ...
substitutor = new StrSubstitutor(m);
result = substitutor.replace(input);
鉴于我想从我的项目中删除 commons-lang 依赖项,使用标准 JRE 库对 StrSubstitutor 进行有效且简约的实现是什么?
注意:
StrSubstitutor 是这样工作的:
Map map = new HashMap();
map.put("animal", "quick brown fox");
map.put("target", "lazy dog");
StrSubstitutor sub = new StrSubstitutor(map);
String resolvedString = sub.replace("The ${animal} jumped over the ${target}.");
yielding resolvedString = "敏捷的棕狐跳过了懒狗。"
【问题讨论】:
-
库简化了你的代码,你为什么要移除依赖?
-
似乎对 entrySet 进行一个简单的循环并调用
inputString.replace("${" + key + "}", value);就可以解决问题(可能不是最有效的方式)。或者从 commons-lang 获取你需要的代码... -
那么问题是什么?
-
“一个有效且简约的实现” - 解析您的字符串以查找相关分隔符并在返回值中替换它们。 - 你能说得更具体点吗?
-
PeterLawrey:assylians 刚刚提供了一个有效的答案。 hoaz:依赖是有问题的,因为它们是可传递的,并且可能与其他库依赖冲突。 hanno-binder:看起来你明白我想要做什么(没有依赖)。