【发布时间】:2010-12-26 22:37:11
【问题描述】:
我正在尝试将包含某些 URL 的字符串替换为与浏览器兼容的链接 URL。
我的初始字符串如下所示:
"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>");
也许正则表达式需要一些修正,但它工作正常,需要进一步测试。
所以问题是如何保持正则表达式捕获的表达式,只需添加创建链接所需的内容:捕获的字符串
提前感谢您的关注和回复!
【问题讨论】:
-
虽然下面的答案应该对您有所帮助,但我建议您查看 John Gruber 的正则表达式,以捕获“在野外”出现的所有形式的 url:daringfireball.net/2009/11/liberal_regex_for_matching_urls
标签: java regex url replace grouping