gpt4 book ai didi

Java:使用正则表达式查找 URL 将它们转换为 html 链接。同时检测链接是否包含http://,如果没有,追加它

转载 作者:行者123 更新时间:2023-12-04 13:59:59 25 4
gpt4 key购买 nike

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

最佳答案

你可以封装mytext到一个对象(比如 MyTextTO )。然后你实现一个方法(比如 getLinkifiedMyText() )来返回 mytext 的链接格式在 MyTextTO 上.你的 MBean 应该有一个 ArrayList<MyTextTO>存储 MyTextTO 的列表将使用 <h:dataTable> 显示在您的 JSF 中.绑定(bind) <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>

关于Java:使用正则表达式查找 URL 将它们转换为 html 链接。同时检测链接是否包含http://,如果没有,追加它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5386682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com