spring中StrSubstitutor更换表达式符号和忽略大小写StrLookup

StrSubstitutor是一个很特殊的类,它使用${}的方法在形成了一个可配置的模板String。首先可以用一个Map声明一个 StrSubstitutor,然后使用replace方法,把模板String中使用${}的部分(内部为Map的key),转化为Map中的值,由此 做到动态更改字符串内容的效果。例如:
 
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);

resolvedString即为替换参数后的字符串内容。
输出结果为:The quick brown fox jumped over the lazy dog.


但是我们需求需要key可以忽略大小写,下面这样就可以了
	       Map<String, String> valuesMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);	
	       valuesMap.put("animal", "quick brown fox");
			valuesMap.put("target", "lazy dog");
			String templateString = "The ${Animal} jumped over the ${target}.";
//			String templateString = "The &{animal} jumped over the &{target}.";
			
			StrSubstitutor sub = new StrSubstitutor(valuesMap);
//			StrSubstitutor sub = new StrSubstitutor(valuesMap, "&(", ")");
			String resolvedString = sub.replace(templateString);
			System.out.println("the str="+resolvedString);	

但是我们是用hashmap的,另外我们表达式不是${Animal}这种,是#{Animal},所以需要改写,

定义一个CaseInsensitiveStrLookup类

public class CaseInsensitiveStrLookup<V> extends StrLookup<V> {

private final Map<String, V> map;

CaseInsensitiveStrLookup(final Map<String, V> map) {
    this.map = map;
}

@Override
public String lookup(final String key) {
    String lowercaseKey = key.toLowerCase(); //lowercase the key you're looking for
    if (map == null) {
        return null;
    }
    final Object obj = map.get(lowercaseKey);
    if (obj == null) {
        return null;
    }
    return obj.toString();
}
}

然后测试

		 Map<String, String> messageValues = new HashMap<String, String>();
		    messageValues.put("killer", "张三");
		    messageValues.put("target", "李四");
//		    StrSubstitutor sub = new StrSubstitutor(new CaseInsensitiveStrLookup<String>(messageValues), "&(", ")", '\\');
		    StrSubstitutor sub = new StrSubstitutor(new CaseInsensitiveStrLookup<String>(messageValues), "#(", ")", '\\');

//		    String format2 = sub.replace("Information: &(killer) killed &(target)!");
		    String format2 = sub.replace("Information: #(killer) killed #(target)!");
		    System.out.println("the str="+format2);	
//		    String format = sub.replace("Information: &(KILLER) killed &(TARGET)!");
		    String format = sub.replace("Information: #(KILLEr) killed #(TARGET)!");
		    System.out.println("the str="+format);	


哦了,key的大小写忽略,使用#{Animal}形式解析,




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值