紅薯老大的小工具:自動爲url添加超鏈的

private final static Pattern url_pattern = Pattern.compile("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?");
/**
 * 自動爲文本中的url生成連接
 * 下載地址:http://www.oschina.net/p/tomcat
 * @param txt
 * @param only_oschina
 * @return
 */
public static String autoMakeLink(String txt, boolean only_oschina) {
	StringBuilder html = new StringBuilder();
	int lastIdx = 0;
	Matcher matchr = url_pattern.matcher(txt);
	while (matchr.find()) {
		String str = matchr.group();			
		html.append(txt.substring(lastIdx, matchr.start()));
		if(!only_oschina || StringUtils.containsIgnoreCase(str, "oschina.net"))
			html.append("<a href='"+str+"' rel='nofollow' target='_blank'>"+str+"</a>");
		else
			html.append(str);
		lastIdx = matchr.end();
	}
	html.append(txt.substring(lastIdx));
	return html.toString();
}
相關文章
相關標籤/搜索