3

我知道这个问题被问了很多,并且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
    }
4

1 回答 1

4

您可以将 封装mytext到一个对象中(比如) 。MyTextTO然后实现一个方法(比如getLinkifiedMyText())来返回mytext. MyTextTO您的 MBean 应该有一个ArrayList<MyTextTO>用于存储MyTextTO将在您的 JSF 中显示的列表,使用<h:dataTable>. 将 的值绑定 <h:outputText>到 后getLinkifiedMyText(),即可显示链接文本。

我参考这个链接来实现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>
于 2011-03-22T06:58:49.823 回答