Wrap/replace url text with anchor tag with java regex

(Updated) After searching some sites, I combined some ideas and came up with this method with an ok regex to find urls in a string and wrap them with anchor tags. I needed this for a chat program that I’m developing.

private static String replaceURLs(String message) {
   String strRegex = "((((https?|ftp|telnet|file):((//)|(\\\\))+)|(www.))+[\\w\\d:#@%/;$()~_?\\+-=\\\\.&]*)";

   if(message != null) {
       StringBuffer str = new StringBuffer(message.length());
       Pattern pattern = Pattern.compile(strRegex);
       Matcher matcher = pattern.matcher(message);

       // Replace urls with anchor tags to the url
       while(matcher.find()) {
           String url = matcher.group(0);

           // Make sure the url isn't part of something else
           int location = message.indexOf(url) + url.length();
           if(location < message.length()) {
              char followingChar = message.charAt(location);
              if(followingChar != ' ') {

       if(!url.substring(0, 4).equalsIgnoreCase("http") &&
          !url.substring(0, 3).equalsIgnoreCase("ftp") &&
          !url.substring(0, 4).equalsIgnoreCase("teln") &&
          !url.substring(0, 4).equalsIgnoreCase("file"))
           url = "http://" + url;

       matcher.appendReplacement(str, Matcher.quoteReplacement("" + url + ""));
    message = str.toString();
    return message;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s