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);
            }
        }
    }

 

 

好了,以上的代碼可以自行實際情況進行修改!

 

代碼改變世界!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM