我知道这些问题会得到很多问题,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
}
答案 0 :(得分:3)
您可以将mytext
封装到一个对象中(比如MyTextTO
)。然后实现一个方法(比如getLinkifiedMyText()
)以返回mytext
的链接格式MyTextTO
。您的MBean应该有ArrayList<MyTextTO>
来存储MyTextTO
的列表,该列表将使用<h:dataTable>
显示在您的JSF中。将<h:outputText>
的值绑定到getLinkifiedMyText()
后,可以显示链接的文本。
我引用this link来实施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>