您好,欢迎来到好走旅游网。
搜索
您的当前位置:首页StrSubstitutor类 字符替换

StrSubstitutor类 字符替换

来源:好走旅游网

StrSubstitutor是一个工具类,它的目的是字符替换

例:

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

替换后值:The quick brown fox jumped over the lazy dog.

StrSubstitutor提供取值分隔符 “:-”,添加到变量的后面

例:

Map values = new HashMap();
 values.put("animal", "quick brown fox");
 values.put("target", "lazy dog");
 
 String template = "The ${animal} jumped over the ${target}. ${undefined.number:-1234}.";
 
 StrSubstitutor sub = new StrSubstitutor(values);
 String resolvedString = sub.replace(template)
替换后:The quick brown fox jumped over the lazy dog. 12345670.

自定义匹配符

如果字符串中的变量形式不是 ${},而是"$()",StrSubstitutor提供了不同的构造器以及setVariablePrefix(char),setVariableSuffix(char)等方法自定义匹配符。

Map values = new HashMap();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
 
String template = "The &(animal) jumped over the &(target). &(undefined.number:-12345670).";
 
StrSubstitutor sub = new StrSubstitutor(values, "&(", ")", '&');
String resolvedString = sub.replace(template);
替换后:The quick brown fox jumped over the lazy dog. 12345670.

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- haog.cn 版权所有 赣ICP备2024042798号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务