Java tutorial
//package com.java2s; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static final Pattern LINK_PATTERN = Pattern .compile("((http://|https://|www\\.).+?)($|\\n|\\r|\\r\\n| )"); /** * Substitutes links in the given text with valid HTML mark-up. For instance, * http://dhis2.org is replaced with <a href="http://dhis2.org">http://dhis2.org</a>, * and www.dhis2.org is replaced with <a href="http://dhis2.org">www.dhis2.org</a>. * * @param text the text to substitute links for. * @return the substituted text. */ public static String htmlLinks(String text) { if (text == null || text.trim().isEmpty()) { return null; } Matcher matcher = LINK_PATTERN.matcher(text); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { String url = matcher.group(1); String suffix = matcher.group(3); String ref = url.startsWith("www.") ? "http://" + url : url; url = "<a href=\"" + ref + "\">" + url + "</a>" + suffix; matcher.appendReplacement(buffer, url); } return matcher.appendTail(buffer).toString(); } /** * Null-safe method for writing the items of a string array out as a string * separated by the given char separator. * * @param array the array. * @param separator the separator of the array items. * @return a string. */ public static String toString(String[] array, String separator) { StringBuilder builder = new StringBuilder(); if (array != null && array.length > 0) { for (String string : array) { builder.append(string).append(separator); } builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } /** * Returns the string representation of the object, or null if the object is * null. * * @param object the object. * @return the string representation. */ public static String toString(Object object) { return object != null ? object.toString() : null; } /** * Invokes append tail on matcher with the given string buffer, and returns * the string buffer as a string. * * @param matcher the matcher. * @param sb the string buffer. * @return a string. */ public static String appendTail(Matcher matcher, StringBuffer sb) { matcher.appendTail(sb); return sb.toString(); } }