• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
深水是沉默
别自制压力,我们没有必要跟着时间走, 只需跟着心态和能力走 随缘 尽力 问心无愧,其他的,交给天。
博客园    首页    新随笔    联系   管理    订阅  订阅
Java 替换String内a标签为指定标签,并提取内容

近段时间遇到一个奇葩的需求,就是需要把富文本里面的a标签提取出来变成小程序的text的标签,然后就在网上找了一些正则来做匹配。

话不多说,直接干代码

 

public static void main(String[] args) {
        String content = "<p>asdfjklasjdflkjaskldf<a href=\"/pages/index/teacherDetail/teacherDetail?id=5fc07aacd9cb485ec9f8ebb0\" target=\"_self\">jklasdjflasd</a></p>";
        Pattern p = Pattern.compile("<a[^>]*>([^<]*)</a>");
        Matcher m = p.matcher(content);
        System.out.println(content);
        String result = "";
        while (m.find()) {
            //System.out.println(m.group(0));
            //System.out.println(m.group(1));
            Pattern p1 = Pattern.compile("<a\\s+href\\s*=\\s*(\"|\')?(.*?)[\"|\'|>]", Pattern.CASE_INSENSITIVE);
            Matcher m1 = p1.matcher(m.group(0));
            while (m1.find()) {
                System.out.println(m.group(0));
                String link = m1.group(2).trim().replace("http://", "");
                String newLink = "<text class=\"beBlue\" bindtap=\"hehe\" data-url=\"{{'"+link+"'}}\" >"+m.group(1)+"</text>";
                System.out.println(newLink);
                result = content.replace(m.group(0), newLink);
                content = content.replace(m.group(0), newLink);
                System.out.println(result);
            }
        }
    }

 

 

好了,以上的代码可以自行实际情况进行修改!

 

代码改变世界!

posted on 2020-12-01 16:05  深水是沉默  阅读(1249)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3