I know this questions get ask a lot, and Kelly Chan
did provide an answer that is work for me, however, there still minor problem that I hope the community can help me out.
For example if a user type this:
Please visit www.google.com
Then I want to convert it into this
Please visit <a href="http://www.google.com">www.google.com</a>
NOTE: that the original text only contain www.google.com
, but I somehow detect that it need to have http://
in front of it. so the link become <a href="http://www.google.com">www.google.com</a>
. If the link is http://www.google.com
, then I just need to wrap it around <a href>
.
EDIT: Kelly Chan
has revised her answer and it work. Below is the solution.
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
}