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

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

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

我想要得到的是一个看起来像这样的字符串:
"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:
String withUrlString = myString.replaceAll(".*://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"null\">HereWasAnURL</a>");

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

因此,问题是如何保持正则表达式捕获表达式并仅添加创建链接所需的内容:catched string

在此先感谢您的关注和回复!

最佳答案

尝试使用:

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

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

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

我问了一个小问题:my question
一些示例:Capturing Text in a Group in a regular expression

09-30 18:48
查看更多