[英]Detect and convert URL in String Java, Is regex better or even faster?
下面的代碼檢測並轉換String中的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;
}
我想我會使用正則表達式,例如:
public static String detectAndConvertURLs(String text) {
//Regex pattern (unescaped), matches any Internet URL:
//((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
Pattern p = Pattern.compile( "((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)" );
Matcher m = p.matcher( text );
if( m.matches() ){
return m.group(1);
}else return null;
}
我只是從這個有用的正則表達式網站上獲取了該正則表達式:
http://regexlib.com/Search.aspx?k=URL
快速的Google搜索將產生許多正則表達式資源:
根據您的使用情況,您可能不得不在開始或結束時稍微按摩一下正則表達式以修剪內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.