Guys,
I know this is not related to Liferay but might be useful in somewhere,
where you need to detect some words and convert it into URL then it would be helpful.
I know this is not related to Liferay but might be useful in somewhere,
where you need to detect some words and convert it into URL then it would be helpful.
public static final String CLOSING_BRACE = "\">" ; public static String detectAndConvertURLs(String text) { String[] parts = text.split("\\s"); String rtn = text; for (String item : parts){ try { // adjustment based one of the answers Pattern urlPattern = Pattern .compile("((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)"); Matcher urlMatcher = urlPattern.matcher(item); if (item.startsWith("@")) { rtn = StringUtil.replace(rtn, item, "<a target=\"_blank\" href=\"http://twitter.com/intent/user?screen_name=" + item.split("@")[1] + CLOSING_BRACE + item + "</a>"); } if (item.startsWith("#")) { rtn = StringUtil.replace(rtn, item, "<a target=\"_blank\" href=\"http://twitter.com/#!/search?q=" + HttpUtil.encodeURL(item) + CLOSING_BRACE + item + "</a>"); } if (urlMatcher.matches()) { item = urlMatcher.group(1); URL url = new URL(item); String link = url.getProtocol() + "://" + url.getHost() + "/" + (url.getPath() == null ? "" : url.getPath()) + (url.getQuery() == null ? "" : "?" + url.getQuery()); rtn = StringUtil.replace(rtn, item, "<a target=\"_blank\" rel=\"nofollow\" href=\"" + link + CLOSING_BRACE + link + "</a> "); } } catch (Exception ignore) { } } return rtn; }