您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

为此使用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>

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

 url.getProtocol();
java 2022/1/1 18:24:14 有446人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶