【发布时间】:2010-11-17 06:18:17
【问题描述】:
下面的代码检测并转换字符串中的 url。有没有更快或更优雅的方式来完成这段代码?:
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 p = Pattern.compile("((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)");
Matcher m = p.matcher(item);
if( m.matches() ) item = m.group(1);
URL url = new URL(item);
String link = url.getProtocol() + "://" + url.getHost() + "/" + (url.getPath() == null ? "" : url.getPath()) + (url.getQuery() == null ? "" : "?" + url.getQuery());
rtn = StringUtils.replace(rtn, item, "<a rel=\"nofollow\" href=\"" + link + "\">" + link + "</a> ");
} catch (MalformedURLException ignore) {
}
return rtn;
}
【问题讨论】:
-
除了速度和优雅方面的考虑之外,此代码也不会检测括号中的 URL,例如
[1][http://www.google.com/]。 -
你在哪里取字符串文本?是长还是短?