java string to 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(""+ url + " " );

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

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

url.getProtocol();

2020-03-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值