この質問はよく聞かれることを知っており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
}