Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : replacing text URL with clickable HTML link

I am trying to do some stuff with replacing String containing some URL to a browser compatible linked URL.

My initial String looks like this :

"hello, i'm some text with an url like http://www.the-url.com/ and I need to have an hypertext link !"

What I want to get is a String looking like :

"hello, i'm some text with an url like <a href="http://www.the-url.com/">http://www.the-url.com/</a> and I need to have an hypertext link !"

I can catch URL with this code line :

String withUrlString = myString.replaceAll(".*://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"null\">HereWasAnURL</a>");

Maybe the regexp expression needs some correction, but it's working fine, need to test in further time.

So the question is how to keep the expression catched by the regexp and just add a what's needed to create the link : catched string

Thanks in advance for your interest and responses !

like image 567
Dough Avatar asked Dec 15 '09 18:12

Dough


2 Answers

public static String textToHtmlConvertingURLsToLinks(String text) {
    if (text == null) {
        return text;
    }

    String escapedText = HtmlUtils.htmlEscape(text);

    return escapedText.replaceAll("(\\A|\\s)((http|https|ftp|mailto):\\S+)(\\s|\\z)",
        "$1<a href=\"$2\">$2</a>$4");
}

There may be better REGEXs out there, but this does the trick as long as there is white space after the end of the URL or the URL is at the end of the text. This particular implementation also uses org.springframework.web.util.HtmlUtils to escape any other HTML that may have been entered.

like image 89
Paul Croarkin Avatar answered Sep 22 '22 13:09

Paul Croarkin


For anybody who is searching a more robust solution I can suggest the Twitter Text Libraries.

Replacing the URLs with this library works like this:

new Autolink().autolink(plainText) 
like image 28
Sonson123 Avatar answered Sep 20 '22 13:09

Sonson123