我将如何转换如下文本或包含 URL(http ftp 等)的任何其他文本
转到此链接http://www.google.com(ofc 堆栈溢出已经这样做了,在我的网站上这只是纯文本);
进入这个
转到此链接
<a href="http://www.google.com">www.google.com</a>
我想出了这个方法
public String transformURLIntoLinks(String text){
String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?";
Pattern p = Pattern.compile(urlValidationRegex);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while(m.find()){
String found =m.group(1); //this String is only made of the http or ftp (just the first part of the link)
m.appendReplacement(sb, "<a href='"+found+"'>"+found+"</a>"); // the result would be <a href="http">"http"</a>
}
m.appendTail(sb);
return sb.toString();
}
问题是我尝试过的正则表达式只匹配第一部分(“http”或“ftp”)。
我的输出变为:Go to this link <a href='http'>http</a>
应该是这个
Go to this link <a href='http://www.google.com'>http://www.google.com</a>