Java:使用正则表达式查找 URL,将其转换为 html 链接。还检测链接是否包含http://,如果不包含,则附加它
我知道这个问题被问了很多,Kelly Chan
确实提供了一个对我有用的答案,但是,仍然有一些小问题,我希望社区可以帮助我解决。
例如,如果用户输入以下内容:
Please visit www.google.com
那么我想将其转换为
Please visit <a href="http://www.google.com">www.google.com</a>
注意:原始文本仅包含www.google.com
,但我以某种方式检测到它前面需要有 http://
。因此链接变为 www.google.com
。如果链接是 http://www.google.com
,那么我只需要将其包裹在 周围。
编辑: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
}
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()<>]+|(\\([^\\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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
mytext
封装到一个对象中(例如MyTextTO
)。然后您实现一个方法(例如getLinkifiedMyText()
)来返回链接化格式MyTextTO
上的mytext
。您的 MBean 应该有一个ArrayList
来存储MyTextTO
列表,该列表将使用
显示在您的 JSF 中> .将
的值绑定到getLinkifiedMyText()
后,即可显示链接化文本。我参考此链接来实现
getLinkifiedMyText ()
:You can encapsulate the
mytext
into an object (sayMyTextTO
) .Then you implement a method (saygetLinkifiedMyText()
) to return the linkified format ofmytext
on theMyTextTO
. Your MBean should has anArrayList<MyTextTO>
to store a list of theMyTextTO
which will be displayed in your JSF using<h:dataTable>
. After you bind the value of the<h:outputText>
to thegetLinkifiedMyText()
, the linkified text can be displayed.I refer to this link to implement the
getLinkifiedMyText()
: