我知道这个问题被问了很多,并且Kelly Chan
确实提供了一个对我有用的答案,但是,仍然存在一些小问题,我希望社区可以帮助我。
例如,如果用户键入:
Please visit www.google.com
然后我想把它转换成这个
Please visit <a href="http://www.google.com">www.google.com</a>
注意:原始文本仅包含www.google.com
,但我以某种方式检测到它需要http://
在它前面。所以链接变成<a href="http://www.google.com">www.google.com</a>
. 如果链接是http://www.google.com
,那么我只需要环绕它<a href>
。
编辑:Kelly Chan
修改了她的答案并且有效。下面是解决方案。
Pattern patt = Pattern.compile("(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'\".,<>???“”‘’]))");
Matcher matcher = patt.matcher(this.mytext);
if(matcher.find()){
if (matcher.group(1).startsWith("http://")){
return matcher.replaceAll("<a href=\"$1\">$1</a>");
}else{
return matcher.replaceAll("<a href=\"http://$1\">$1</a>");
}
}else{
return this.mytext
}