Java:用可点击的HTML链接替换文本URL [英] Java : replacing text URL with clickable HTML link

查看:90
本文介绍了Java:用可点击的HTML链接替换文本URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过将包含某些URL的String替换为与浏览器兼容的链接URL来做些事情.

I am trying to do some stuff with replacing String containing some URL to a browser compatible linked URL.

我的初始String看起来像这样:

My initial String looks like this :

"hello, i'm some text with an url like http://www.the-url.com/ and I need to have an hypertext link !"

我想要得到的是一个看起来像这样的字符串:

What I want to get is a String looking like :

"hello, i'm some text with an url like <a href="http://www.the-url.com/">http://www.the-url.com/</a> and I need to have an hypertext link !"

我可以使用以下代码行捕获URL:

I can catch URL with this code line :

String withUrlString = myString.replaceAll(".*://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"null\">HereWasAnURL</a>");

也许regexp表达式需要一些更正,但是它工作正常,需要进一步测试.

Maybe the regexp expression needs some correction, but it's working fine, need to test in further time.

所以问题是如何使正则表达式捕获表达式并仅添加创建链接所需的内容:捕获的字符串

So the question is how to keep the expression catched by the regexp and just add a what's needed to create the link : catched string

提前感谢您的关注和回复!

Thanks in advance for your interest and responses !

推荐答案

尝试使用:

myString.replaceAll("(.*://[^<>[:space:]]+[[:alnum:]/])", "<a href=\"$1\">HereWasAnURL</a>");

我没有检查您的正则表达式.

I didn't check your regex.

通过使用(),您可以创建组. $1表示组索引. $1将替换网址.

By using () you can create groups. The $1 indicates the group index. $1 will replace the url.

我问了一个小问题:我的问题
一些示例:以正则表达式捕获组中的文本

I asked a simalir question: my question
Some exemples: Capturing Text in a Group in a regular expression

这篇关于Java:用可点击的HTML链接替换文本URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆