Java检测url
我正在尝试用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];
}
I'm trying to make it in java so that if I type a message that contains a link it automaticly formats it with html so it can be clickable on a webpage :P
However, the code i have written only turns the first "link" in my message to a link, not the others.
Can someone help me with this? I'm out of ideas...
My Code
// 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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
replaceAll()
而不是replace()
。编辑:
您可以使用像这样的正则表达式来更简单、更干净,而不是使用 split :
Use
replaceAll()
instead ofreplace()
.EDIT :
You can do it way simpler and cleaner with regex like this, instead of using splits :
对于附加图像,您可以使用两次替换(第二次替换为负向后查找:
为您提供:
For the additional images, you could use two replaces (with a negative look-behind for the second replace:
Gives you: