Java: using regex to find URL turning them into html link. Also detect if link contain http://, If not, append it
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()<>]+|(\\(开发者_StackOverflow社区[^\\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
}
You can encapsulate the mytext
into an object (say MyTextTO
) .Then you implement a method (say getLinkifiedMyText()
) to return the linkified format of mytext
on the MyTextTO
. Your MBean should has an ArrayList<MyTextTO>
to store a list of the MyTextTO
which will be displayed in your JSF using <h:dataTable>
. After you bind the value of the <h:outputText>
to the getLinkifiedMyText()
, the linkified text can be displayed.
I refer to this link to implement the getLinkifiedMyText()
:
public class MyTextTO{
private String mytext;
/**Getters , setters and constructor**/
public String getLinkifiedMyText(){
try {
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.group(1).startsWith("http://")){
return matcher.replaceAll("<a href=\"$1\">$1</a>");
}else{
return matcher.replaceAll("<a href=\"http://$1\">$1</a>");
}
} catch (Exception e) {
return this.mytext;
}
}
}
<h:dataTable value="#{bean.dataList}" var="row">
<h:column>
<h:outputText value="#{row.linkifiedMyText}" escape="false" />
</h:column>
</h:dataTable>
精彩评论