我是靠谱客的博主 俭朴泥猴桃,这篇文章主要介绍String类用到正则的方法及利用正则写的模板引擎,现在分享给大家,希望可以做个参考。

文章目录

      • String类中方法用到的正则
      • 模板引擎

String类中方法用到的正则

  • replaceAll
  • replaceFirst
  • split
    上述方法若匹配正则表达式中的字符均需转义
    replace和replaceAll都是取代所有的字符。replace的第一个参数是字符串,replaceAll的第一个参数是正则表达式
    看一下replaceAll的源码
复制代码
1
2
3
4
5
public String replaceAll(String regex, String replacement) { //实质上调用的就是 return Pattern.compile(regex).matcher(this).replaceAll(replacement); }

replace的源码,介绍之前先熟悉一下Pattern类中的匹配模式
单行模式(点号模式)、多行模式、大小写无关模式、特殊字符作为普通字符处理模式,它们对应的常量分别为:Pattern.DOTALL,Pattern.MULTILINE、Pattern.CASE_INSENSITIVE、Pattern.LITERAL,多个模式可以一起使用,通过’|'连起来即可。

Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL)

复制代码
1
2
3
4
5
6
public String replace(CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( this).replaceAll(Matcher.quoteReplacement(replacement.toString())); }

Pattern.compile(target.toString(), Pattern.LITERAL)匹配时把正则特殊字符转为普通字符。
Matcher.quoteReplacement 匹配的结果特殊字符转为普通字符主要是$和。

模板引擎

①logger中打印日志。
比如

复制代码
1
2
3
4
//以{}来作为参数的替代 logger.info("### 输入的省份名provinceName{}",provinceName);

仿写:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static String moduleLogger(String str, Object... args) { //正则表达式 String regx = "\{\}"; Pattern pattern = Pattern.compile(regx); Matcher matcher = pattern.matcher(str); //只能用StringBuffer StringBuffer sb = new StringBuffer(); //边查找边替换 int foundNum=0; while (matcher.find()) { //可变参数的本质是数组 matcher.appendReplacement(sb, Matcher.quoteReplacement(args[foundNum++].toString())); } //添加尾部 matcher.appendTail(sb); return sb.toString(); }

②使用Map中的value替换字符串中的{key}。
形如字符串:“Hi {name}, your code is {code}.”;

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static String templateEngine(String template, Map<String, String> paramsMap) { Pattern templatePattern = Pattern.compile("\{(\w+)\}"); StringBuffer sb = new StringBuffer(); Matcher matcher = templatePattern.matcher(template); while (matcher.find()) { //取出key String key = matcher.group(1); //从对应的Map中获取value String value = paramsMap.get(key); matcher.appendReplacement(sb, value != null ? Matcher.quoteReplacement(value.toString()) : ""); } matcher.appendTail(sb); return sb.toString(); }

测试

复制代码
1
2
3
4
5
6
7
8
9
10
String moduleStr = "### 输入的省份名provinceName为:{}" System.out.println(moduleLogger(moduleStr,"安徽")); String template = "Hi {name}, your code is {code}."; Map<String, Object> params = new HashMap<String, Object>(); params.put("name", "老马"); params.put("code", 6789); System.out.println(templateEngine(template, params));

以上就是两个小例子了,有更好的例子请留言。

参考资料:

老马说编程

每篇一语

几时归去,作个闲人。对一张琴,一壶酒,一溪云。——《行香子·述怀》苏轼

最后

以上就是俭朴泥猴桃最近收集整理的关于String类用到正则的方法及利用正则写的模板引擎的全部内容,更多相关String类用到正则内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(86)

评论列表共有 0 条评论

立即
投稿
返回
顶部