点击登录,精彩内容等着你

Java Pattern类正则表达式匹配理解,通过简单方式理解该类的使用

全栈侠客

2022-09-19
本站介绍Pattern通过正则来对html的特定元素进行赋值,修改等操作,理解该类的基本使用方法

leanboot精益编程系统,是通过editoermd来进行markdown的文章编辑,

  • toc是本编辑器特有的目录功能,需求是需要提取toc出来,独立显示。
  • 对文章的一些特有属性,如img.src等,有时候需要修改前缀地址,都可以使用该方法进行查找与替换
  • 虽然有其他更加方便的方法,如使用jsoup来解析html,来获取对应的便签进行统一修改

一、java.util.regex.Pattern类

1. 匹配模式与匹配器

方法:Pattern.compile(String regex, int flags)

  • regex : 正则表达式
  • flags :匹配模式标识,通常使用Pattern.CASE_INSENSITIVE,为大小写不敏感匹配
  1. //1.正则表达式
  2. // tag为标签名
  3. String regix = "<" + tag + "[^>]*?>[\\s\\S]*?<\\/" + tag + ">";
  4. //2.匹配模式
  5. Pattern pattern = Pattern.compile(regix, Pattern.CASE_INSENSITIVE);
  6. //3.匹配器
  7. Matcher matcher = pattern.matcher(html);

2.去除匹配标签

  1. //2.5 过滤特定标签
  2. public static String clearTag(String html,String tag) {
  3. String regix = "<" + tag + "[^>]*?>[\\s\\S]*?<\\/" + tag + ">";
  4. if(StringUtils.isBlank(html)) {
  5. return "";
  6. }
  7. Pattern p_space = Pattern.compile(regix, Pattern.CASE_INSENSITIVE);
  8. Matcher m_space = p_space.matcher(html);
  9. html = m_space.replaceAll(""); // 过滤空格回车标签
  10. return html.trim();
  11. }

3.替换

通常用于对一些标签进行替换操作,如文章中不允许直接发布对外链接,可以把链接转一下

  1. <a href="www.baidu.com">百度</a> 转化为:
  2. [百度](www.baidu.com)

代码如下:

  1. public static String linkOpen(String html) {
  2. if(StringUtils.isBlank(html)) {
  3. return "";
  4. }
  5. String regEx_a = "<a[^>]*?>[\\s\\S]*?<\\/a>";
  6. //1.正则匹配
  7. Pattern p_slot = Pattern.compile(regEx_a, Pattern.CASE_INSENSITIVE);
  8. Matcher matcherSlot = p_slot.matcher(html);
  9. //2.循环查找
  10. StringBuffer sb = new StringBuffer();
  11. boolean result = matcherSlot.find();
  12. while (result) {
  13. //1.获取slot.key
  14. String aHtml = matcherSlot.group();
  15. //2.组装替换内容
  16. String replaceMent = "[" + HtmlUtils.getInText(aHtml, "a") + "](";
  17. replaceMent += HtmlUtils.getAttr(aHtml, "a", "href") + ")";
  18. //3.替换标签(等于修改找到匹配结果)
  19. matcherSlot.appendReplacement(sb,replaceMent);
  20. result = matcherSlot.find();
  21. }
  22. matcherSlot.appendTail(sb);
  23. return sb.toString();
  24. }

4.appendReplacement()和appendTail()用法

  • appendReplacement:将当前匹配的子字符串替换为指定的字符串,并且将替换后的字符串及其之前到上次匹配的子字符串之后的字符串添加到一个StringBuffer对象中。

  • appendTail:将最后一次匹配之后剩余的字符串添加到一个StringBuffer对象中。

总结:

  • 掌握一些regex正则表达式的一些用法
  • 掌握这一种布局匹配,局部替换的基本操作
  • 本章只做抛砖引玉,其他深奥的用法请自行度量

小经验:

  • 东西够用就行,多的只要有一个基本了解,或者只要让你判断:能做还是不能做的就行
  • 当真正遇到一些问题的时候,再来查询其他方法都不迟哦
阅读 810     最后编辑 2022-09-26 21:46
文章补充
评论(0) 发表新评论
  • ...暂无评论...

我是有底线的 评论与点赞5分钟更新一次
回复评论
取消关闭

请先登录