java - 如何检测字符串中是否存在 URL

标签 java url

我有一个输入字符串,比如 Please go to http://stackoverflow.com .检测到字符串的 url 部分和一个 anchor <a href=""></a>由许多浏览器/IDE/应用​​程序自动添加。所以它变成了Please go to <a href='http://stackoverflow.com'>http://stackoverflow.com</a> .

我需要使用 Java 做同样的事情。

最佳答案

为此使用 java.net.URL!!

嘿,为什么不为这个“java.net.URL”使用java中的核心类并让它验证URL。

虽然以下代码违反了“仅在异常情况下使用异常”这一黄金原则,但尝试为 Java 平台上非常成熟的东西重新发明轮子对我来说是没有意义的。

代码如下:

import java.net.URL;
import java.net.MalformedURLException;

// Replaces URLs with html hrefs codes
public class URLInString {
    public static void main(String[] args) {
        String s = args[0];
        // separate input by spaces ( URLs don't have spaces )
        String [] parts = s.split("\\s+");

        // Attempt to convert each item into an URL.   
        for( String item : parts ) try {
            URL url = new URL(item);
            // If possible then replace with anchor...
            System.out.print("<a href=\"" + url + "\">"+ url + "</a> " );    
        } catch (MalformedURLException e) {
            // If there was an URL that was not it!...
            System.out.print( item + " " );
        }

        System.out.println();
    }
}

使用以下输入:

"Please go to http://stackoverflow.com and then mailto:oscarreyes@wordpress.com to download a file from    ftp://user:pass@someserver/someFile.txt"

产生以下输出:

Please go to <a href="http://stackoverflow.com">http://stackoverflow.com</a> and then <a href="mailto:oscarreyes@wordpress.com">mailto:oscarreyes@wordpress.com</a> to download a file from    <a href="ftp://user:pass@someserver/someFile.txt">ftp://user:pass@someserver/someFile.txt</a>

当然,不同的协议(protocol)可以以不同的方式处理。 您可以使用 URL 类的 getter 获取所有信息,例如

 url.getProtocol();

或其他属性:spec、port、file、query、ref 等

http://java.sun.com/javase/6/docs/api/java/net/URL.html

处理所有协议(protocol)(至少所有这些 java 平台都知道),并且作为额外的好处,如果存在 java 当前无法识别并最终被合并到 URL 类中的任何 URL(通过库更新)你'会透明地得到它!

关于java - 如何检测字符串中是否存在 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/285619/

相关文章:

c# - 如何从网址下载图片

Java - 如何找到网址的重定向网址?

python - 在 django 开发服务器上工作,但不在 apache 上工作

java - 如何将像 Quickfixj 这样的 TCP 服务器实现集成到 Spring-Integration 项目中?

java - Glassfish 在 OS X 10.5/Java 6 上挂起

具有相同名称的 Java 枚举和字段

java - 在圆圈内绘制随机点

javascript - 将 URL 参数传递给 Python

javascript - 如何在地址栏上显示不同网址的新窗口中打开链接

java - 我的程序跳过让用户输入一个变量的值