Java:用可点击的HTML链接替换文本URL

我正在尝试将包含某些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 http://www.the-url.com/ and I need to have an hypertext link !" 

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

 String withUrlString = myString.replaceAll(".*://[^[:space:]]+[[:alnum:]/]", "HereWasAnURL"); 

也许regexp表达式需要一些修正,但它工作正常,需要在更长的时间内进行测试。

所以问题是如何保持regexp捕获的表达式,只需添加创建链接所需的内容:catched string

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

尝试使用:

 myString.replaceAll("(.*://[^<>[:space:]]+[[:alnum:]/])", "HereWasAnURL"); 

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

通过使用()您可以创建组。 $1表示组索引。 $1将取代url。

我问了一个simalir问题: 我的问题
一些例子: 在正则表达式中捕获组中的文本

 public static String textToHtmlConvertingURLsToLinks(String text) { if (text == null) { return text; } String escapedText = HtmlUtils.htmlEscape(text); return escapedText.replaceAll("(\\A|\\s)((http|https|ftp|mailto):\\S+)(\\s|\\z)", "$1https://stackoverflow.com/questions/1909534/java-replacing-text-url-with-clickable-html-link/$2$4"); } 

可能有更好的REGEX,但只要在URL结尾后有空格或URL在文本的末尾,这就可以解决问题。 此特定实现还使用org.springframework.web.util.HtmlUtils来转义可能已输入的任何其他HTML。

对于正在搜索更强大的解决方案的任何人,我可以推荐Twitter文本库 。

用这个库替换URL的工作方式如下:

 new Autolink().autolink(plainText) 

Belows代码替换以“http”或“https”开头的链接,链接仅以“www”开头。 最后还替换了电子邮件链接。

  Pattern httpLinkPattern = Pattern.compile("(http[s]?)://(www\\.)?([\\S&&[^.@]]+)(\\.[\\S&&[^@]]+)"); Pattern wwwLinkPattern = Pattern.compile("(?$0"); final Matcher wwwLinksMatcher = wwwLinkPattern.matcher(textWithHttpLinksEnabled); textWithHttpLinksEnabled = wwwLinksMatcher.replaceAll("$0"); final Matcher mailLinksMatcher = mailAddressPattern.matcher(textWithHttpLinksEnabled); textWithHttpLinksEnabled = mailLinksMatcher.replaceAll("$0"); System.out.println(textWithHttpLinksEnabled); } 

打印:

 ajdhkas www.dasda.pl/asdsad?asd=sd www.absda.pl maiandrze@asdsa.pl klajdld http://dsds.pl httpsda http://www.onet.pl https://www.onsdas.plad/dasda 

假设您的正则表达式可以捕获正确的信息,您可以在替换中使用反向引用。 请参阅Java regexp教程 。

在那种情况下,你会这样做

 myString.replaceAll(.....,“ \ 1 ”)

如果是多行文字,您可以使用:

 text.replaceAll("(\\s|\\^|\\A)((http|https|ftp|mailto):\\S+)(\\s|\\$|\\z)", "$1https://stackoverflow.com/questions/1909534/java-replacing-text-url-with-clickable-html-link/$2$4"); 

这里是我的代码的完整示例,我需要在其中显示带有URL的用户post:

 private static final Pattern urlPattern = Pattern.compile( "(\\s|\\^|\\A)((http|https|ftp|mailto):\\S+)(\\s|\\$|\\z)"); String userText = ""; // user content from db String replacedValue = HtmlUtils.htmlEscape(userText); replacedValue = urlPattern.matcher(replacedValue).replaceAll("$1https://stackoverflow.com/questions/1909534/java-replacing-text-url-with-clickable-html-link/$2$4"); replacedValue = StringUtils.replace(replacedValue, "\n", "
"); System.out.println(replacedValue);