字符替换,可以使用正则表达式对匹配的字符进行替换,这种方式比较灵活。而StrSubstitutor是一个工具类,它的目的也是字符替换,但是它封装了由正则表达式灵活性带来的复杂性,从而以更简单,通用的方式组织数据。
首先,明确它是apache工具包下的一个类;然后来学习学习它的简单调用。
1 简单的调用。
Map valuesMap = new HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
output print
The quick brown fox jumped over the lazy dog.
2 简单的调用-设置变量的默认值
字符串的变量如果在Map实体中找到对应的Key值,变量就不会被替换,而是直接以字符串展示。StrSubstitutor提供取值分隔符 ":-",添加到变量的后面。例如 ${undefined.number:-1234567890}.
Map valuesMap = new HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
output
The quick brown fox jumped over the lazy dog. 1234567890.
StrSubstitutor提供了setValueDelimiterMatcher(StrMatcher), setValueDelimiter(char) or setValueDelimiter(String)三种方法,可以自定义默认取值分隔符。
3 简单的调用-自定义匹配符
如果字符串中的变量形式不是 "${}",而是"$()",StrSubstitutor提供了不同的构造器以及setVariablePrefix(char),setVariableSuffix(char)等方法自定义匹配符。
Map valuesMap = new HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The &(animal) jumped over the &(target). &(undefined.number:-1234567890).";
StrSubstitutor sub = new StrSubstitutor(valuesMap, "&(", ")", '&');
String resolvedString = sub.replace(templateString);
output
The quick brown fox jumped over the lazy dog. 1234567890.
4 一般的调用-自定义实体类
在系统中装载数据的实体有可能不是Map,而是其它的数据实体,例如com.fasterxml.jackson.databind.node.JsonNode。
public class StrSubstitutorTest {
@Test
public void test() {
StrSubstitutor substitutor = new StrSubstitutor();
ObjectNode context = JsonNodeFactory.instance.objectNode();
context.put("animal", "quick brown fox");
context.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.";
substitutor.setVariableResolver(new JsonPathContextLookup(context));
String resolvedString = substitutor.replace(templateString);
System.out.println(resolvedString);
}
class JsonPathContextLookup extends StrLookup<String> {
private final JsonNode context;
JsonPathContextLookup(JsonNode context) {
super();
this.context = context;
}
@Override
public String lookup(String key) {
return Optional.ofNullable(context.get(key)).map(JsonNode::asText).orElse(null);
}
}
}
output
The quick brown fox jumped over the lazy dog. 1234567890.
StrSubstitutor的使用非常的方便,简单,可以当作一个模板工具使用。该工具就就介绍完了,我觉得写博客是一个好习惯,它能加深自己对一个东西的理解。在一个系统中,如果看到一个未接触过的功能,刚开始接触时,往往会有一种心理压力,表现出畏难情绪,我认为这再正常不过了,毕竟人对未知不仅是充满了好奇,还有害怕。
坚持每个月至少两篇博客的习惯,多学习学习,思考思考总是好的。