2011-11-04 68 views
0

我试图使它在Java中,因此当我键入包含它与全自动HTML格式,以便它可以在网页上点击一个链接的消息:PJava的检测URL

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

有人可以帮助我吗?我的想法......

我的代码

// 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]; 
} 
+0

另外,请记住,并非所有网址都以“http://”开头(除非您是唯一一个添加内容并可以保证您始终记住http://)的网址。你可以找到一些漂亮的正则表达式与一些谷歌搜索,虽然我从来没有找到一个完美的。 –

回答

1

使用replaceAll()而不是replace()

编辑:

你可以做到这一点的方法更简单和更清洁的,像这样的正则表达式,而不是使用分裂:

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

现在只有最后一个是链接,第一个不是... –

+0

我编辑了我的回复。 – kgautron

+0

也许!但现在,如果我张贴图像链接和常规链接,火焰之一会改变另一个...如果我张贴图像链接,然后链接都转向图像.... 我目前的代码:http:// pastebin.com/xsiPiuAM –

0

对于更多的图像,就可以使用两个将取代(带负外观-behind第二替换:

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> 
+0

它可能能够在JavaScript中做到这一点呢? :P它会是相同的代码? –

+0

,如果我使用这个。如何实现我的YouTube检测代码? –

+0

@enjikaka:Javascript没有实现负向后视('(?<!img src = \“)'位,所以它会有点不同。尽管我会说这是另一个问题。 – beny23