Java:使用正则表达式查找将其转换为html链接的URL。还检测链接是否包含http://,如果不包含,请附加它

时间:2011-03-22 04:07:43

标签: java regex linkify

我知道这些问题会得到很多问题,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
    }

1 个答案:

答案 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>