栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

为此使用java.net.URL!
嘿,为什么不对这个“ java.net.URL”使用Java的核心类,而让它验证URL。

尽管以下代码违反了“仅在特殊情况下使用异常”这一黄金原则,但对Java平台上已经成熟的某些东西而言,尝试重新发明轮子却无济于事。

这是代码:

import java.net.URL;import java.net.MalformedURLException;// Replaces URLs with html hrefs prespublic 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();


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号