【问题标题】:Java detect urlJava检测url
【发布时间】:2011-12-22 00:06:24
【问题描述】:

我正在尝试在 java 中制作它,这样如果我输入包含链接的消息,它会自动使用 html 格式化它,以便可以在网页上点击它:P

但是,我编写的代码仅将消息中的第一个“链接”转换为链接,而不是其他链接。

有人可以帮我解决这个问题吗?我没有想法......

我的代码

// URL and Image handling
    if (msg.contains("http://")) {
        // If url is an image, embed it
        if (msg.contains(".jpg") || msg.contains(".png") || msg.contains(".gif")) {
            msg = msg.replace(linkz(msg, true), "<img src='" + linkz(msg, true) + "' class='embedded-image' />");
        }
        // Send link as link in <a> tag
        msg = msg.replace(linkz(msg, true), "<a href='" + linkz(msg, true) + "' class='msg-link' target='_blank' title='" + linkz(msg, false) + "'>" + linkz(msg, false) + "</a>");
    }

// Check string for links and return the link
public static String linkz(String msg, boolean http) {
    String[] args = msg.split("http://");
    String[] arg = args[1].split(" ");
    if (http == true) {
        return "http://" + arg[0];
    }
    return arg[0];
}

【问题讨论】:

  • 另外,请记住,并非所有 URL 都以“http://”开头(除非您是唯一添加内容的人,并且可以保证您将永远记住 http://)。你可以通过一些谷歌搜索找到一些非常好的正则表达式,虽然我从来没有找到一个完美的。

标签: java http url hyperlink href


【解决方案1】:

对于其他图像,您可以使用两个替换(第二个替换为否定的后视:

String msg = 
    "this is an example https://test.com/img.jpg " +
    "for http://www.test.com/ and yet more " +
    "http://test/test/1/2/3.img.gif test and more " +
    "https://www.test.com/index.html";

// replace images with img tag 
msg = msg.replaceAll(
    "https?://[^ ]+\\.(gif|jpg|png)", 
    "<img src=\"$0\" class=\"embedded-image\" />");

msg = msg.replaceAll("(?<!img src=\")https?://([^ ]+)", 
    "<a href=\"$0\" class=\"msg-link\" target=\"_blank\" title=\"$1\">$1</a>");

System.out.println(msg);

给你:

this is an example <img src="https://test.com/img.jpg" class="embedded-image" /> 
for <a href="http://www.test.com/" class="msg-link" target="_blank" 
title="www.test.com/">www.test.com/</a> and yet more 
<img src="http://test/test/1/2/3.img.gif" class="embedded-image" /> 
test and more <a href="https://www.test.com/index.html" class="msg-link" 
target="_blank" title="www.test.com/index.html">www.test.com/index.html</a>

【讨论】:

  • 它也许可以在 javascript 中执行此操作吗? :P 会是相同的代码吗?
  • 如果我使用它。如何实现我的 youtube 检测代码?
  • @enjikaka:Javascript 没有实现负面的后视((?&lt;!img src=\") 位,所以会有点不同。虽然我会说这是另一个问题。
【解决方案2】:

使用replaceAll() 而不是replace()

编辑:

您可以使用这样的正则表达式更简单、更清洁,而不是使用拆分:

msg.replaceAll("http://[^ ]+", "<a href=\"$0\">$0</a>");

【讨论】:

  • 是的!但是现在如果我发布一个图片链接和一个常规链接,最火的一个会改变另一个……如果我发布一个图片链接,然后一个链接都变成了图片……我当前的代码:pastebin.com/xsiPiuAM
  • getLinks() 在名为 CheckLinks.class 的类中,而 check() 在 Handler.class 中
  • 您可以在正则表达式的末尾添加类似 '(png|jpg|etc...)' 的内容,以检查链接是否对应于图片。
猜你喜欢
  • 2011-06-15
  • 2011-06-17
  • 2017-02-02
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2012-12-30
相关资源
最近更新 更多