【问题标题】:Java : replacing text URL with clickable HTML linkJava:用可点击的 HTML 链接替换文本 URL
【发布时间】: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>");

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

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

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

【问题讨论】:

标签: java regex url replace grouping


【解决方案1】:

尝试使用:

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

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

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

我问了一个类似的问题:my question
一些例子:Capturing Text in a Group in a regular expression

【讨论】:

  • 这不适用于文本中的多个链接,因为.* 占用太多。
【解决方案2】:
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。

【讨论】:

  • 不适用于仅由一个空格分隔的两个链接。
【解决方案3】:

对于正在寻找更强大解决方案的任何人,我可以建议Twitter Text Libraries

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

new Autolink().autolink(plainText) 

【讨论】:

  • url 格式必须正确。无法检测到:www.example.com(http:// 缺失)。 :(
【解决方案4】:

以下代码替换以“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>

【讨论】:

    【解决方案5】:

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

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

    myString.replaceAll(....., "\1")

    【讨论】:

      【解决方案6】:

      如果是多行文本,你可以使用这个:

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

      这是我的代码的完整示例,我需要在其中显示带有 url 的用户帖子:

      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);
      

      【讨论】:

        猜你喜欢
        • 2013-02-18
        • 2015-04-12
        • 2014-02-22
        • 1970-01-01
        • 2014-08-01
        • 1970-01-01
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多