且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测字符串中URL的存在

更新时间:2023-02-18 17:08:42

使用java.net .URL for that !!



嘿,为什么不在java中使用核心类来获取这个java.net.URL并让它验证URL。

Use java.net.URL for that!!

Hey, why don't use the core class in java for this "java.net.URL" and let it validate the URL.

虽然以下代码违反了黄金原则仅针对异常条件使用例外,但对于我来说,尝试重新发明***以获得成熟的东西是没有意义的在java平台上。

While the following code violates the golden principle "Use exception for exceptional conditions only" it does not make sense to me to try to reinvent the wheel for something that is veeery mature on the java platform.

这是代码:

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://***.com and then mailto:oscarreyes@wordpress.com to download a file from    ftp://user:pass@someserver/someFile.txt"

产生以下输出:

Please go to <a href="http://***.com">http://***.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>

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

Of course different protocols could be handled in different ways. You can get all the info with the getters of URL class, for instance

 url.getProtocol();

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

Or the rest of the attributes: spec, port, file, query, ref etc. etc

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

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

Handles all the protocols ( at least all of those the java platform is aware ) and as an extra benefit, if there is any URL that java currently does not recognize and eventually gets incorporated into the URL class ( by library updating ) you'll get it transparently!