how to replace plain url with hyperlinks in html doc

我的未来我决定 提交于 2019-12-04 20:06:10

I would recommand you to use Jsoup here.

Sample code

String text = "<html><head></head><body><a href='http://google.com'>Don't change this link</a> Change this: http://yahoo.com foo.com</body></html>";
Document d = Jsoup.parse(text);
String newHtmlCode = "";
String oldHtmlCode = d.outerHtml();
List<TextNode> textNodes = d.body().textNodes();

Matcher m = Patterns.WEB_URL.matcher("");
for (TextNode textNode : textNodes) {
    m.reset(textNode.text());

    String fragment = "";
    while (m.find()) {
        fragment = m.replaceAll("<a href=\"\\*\\*\\*$1\">$1</a>");
        textNode.replaceWith(new Element(Tag.valueOf("span"),"").html(fragment));
    }

    newHtmlCode = d.outerHtml().replaceAll("\"\\Q***\\E(?!https?://)", "\"http://").replaceAll("\"\\Q***\\E(https?://)", "\"$1");
}

System.out.println("BEFORE:\n\n" + oldHtmlCode);
System.out.println("----------------------------");
System.out.println("AFTER:\n\n" + newHtmlCode);

Output

BEFORE:

<html>
 <head></head>
 <body>
  <a href="http://google.com">Don't change this link</a> Change this: http://yahoo.com foo.com
 </body>
</html>
----------------------------
AFTER:

<html>
 <head></head>
 <body>
  <a href="http://google.com">Don't change this link</a>
  <span> Change this: <a href="http://yahoo.com">http://yahoo.com</a> <a href="http://foo.com">foo.com</a></span>
 </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!