近段時間遇到一個奇葩的需求,就是需要把富文本里面的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); } } }
好了,以上的代碼可以自行實際情況進行修改!
代碼改變世界!