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

12

我正在尝试将包含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:http://daringfireball.net/2009/11/liberal_regex_for_matching_urls - FRotthowe
6个回答

7

尝试使用:

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

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

通过使用 (),您可以创建分组。 $1 表示组索引。 $1 将替换 url。

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


这对于文本中的多个链接不起作用,因为 .* 太多了。 - Sonson123

7
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)",
        "$1<a href=\"$2\">$2</a>$4");
}

可能有更好的正则表达式,但只要在URL结尾后有空格或URL在文本末尾,这个正则就可以起作用。此实现还使用org.springframework.web.util.HtmlUtils转义可能输入的任何其他HTML。

1
仅通过一个空格分隔的两个链接无法正常工作。 - Sonson123

5

如果您正在寻找更强大的解决方案,我可以推荐Twitter Text Libraries

使用该库替换URL的方法如下:

new Autolink().autolink(plainText) 

网址必须格式正确。无法检测到:www.example.com(缺少http://)。:( - redochka

2
以下代码替换以“http”或“https”开头的链接,以“www。”开头的链接,最后还替换了电子邮件链接。
  Pattern httpLinkPattern = Pattern.compile("(http[s]?)://(www\\.)?([\\S&&[^.@]]+)(\\.[\\S&&[^@]]+)");

  Pattern wwwLinkPattern = Pattern.compile("(?<!http[s]?://)(www\\.+)([\\S&&[^.@]]+)(\\.[\\S&&[^@]]+)");

  Pattern mailAddressPattern = Pattern.compile("[\\S&&[^@]]+@([\\S&&[^.@]]+)(\\.[\\S&&[^@]]+)");

    String 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";

    if (Objects.nonNull(textWithHttpLinksEnabled)) {

      Matcher httpLinksMatcher = httpLinkPattern.matcher(textWithHttpLinksEnabled);
      textWithHttpLinksEnabled = httpLinksMatcher.replaceAll("<a href=\"$0\" target=\"_blank\">$0</a>");

      final Matcher wwwLinksMatcher = wwwLinkPattern.matcher(textWithHttpLinksEnabled);
      textWithHttpLinksEnabled = wwwLinksMatcher.replaceAll("<a href=\"http://$0\" target=\"_blank\">$0</a>");

      final Matcher mailLinksMatcher = mailAddressPattern.matcher(textWithHttpLinksEnabled);
      textWithHttpLinksEnabled = mailLinksMatcher.replaceAll("<a href=\"mailto:$0\">$0</a>");

      System.out.println(textWithHttpLinksEnabled);
    }

输出:

ajdhkas <a href="http://www.dasda.pl/asdsad?asd=sd" target="_blank">www.dasda.pl/asdsad?asd=sd</a> <a href="http://www.absda.pl" target="_blank">www.absda.pl</a> <a href="mailto:maiandrze@asdsa.pl">maiandrze@asdsa.pl</a> klajdld <a href="http://dsds.pl" target="_blank">http://dsds.pl</a> httpsda <a href="http://www.onet.pl" target="_blank">http://www.onet.pl</a> <a href="https://www.onsdas.plad/dasda" target="_blank">https://www.onsdas.plad/dasda</a>

1
假设您的正则表达式可以捕获正确的信息,您可以在替换中使用反向引用。请参见Java regexp tutorial
在这种情况下,您可以执行以下操作:
myString.replaceAll(....., "<a href=\"\1\">\1</a>")

0

如果有多行文本,您可以使用以下方法:

text.replaceAll("(\\s|\\^|\\A)((http|https|ftp|mailto):\\S+)(\\s|\\$|\\z)",
        "$1<a href='$2'>$2</a>$4");

这里是我的完整代码示例,我需要在其中显示用户帖子及其链接:

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("$1<a href=\"$2\">$2</a>$4");
replacedValue = StringUtils.replace(replacedValue, "\n", "<br>");
System.out.println(replacedValue);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接