maven引用
<dependency>
<groupId>io.github.url-detector</groupId>
<artifactId>url-detector</artifactId>
<version>0.1.23</version>
</dependency>
public class TestController {
private static String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则
public static void main(String[] args) {
String text = "做款手机的提问时,罗永浩回复称:因https://www.baidu.com为要烧投资人的钱,所以我确实没这勇气了。aa.cn/nha?1234确认";
List<Url> found = parser(text);
for (Url url : found) {
System.out.println("Scheme: " + url.getScheme());
System.out.println("Host: " + url.getHost());
System.out.println("Path: " + url.getPath());
}
}
private static List<Url> parser(String text) {
text = text.replaceAll(REGEX_CHINESE, " ");
// System.out.println("replace text: " + text);
UrlDetector parser = new UrlDetector(text, UrlDetectorOptions.Default);
List<Url> found = parser.detect();
return found;
}
}
运行结果:
Scheme: https
Host: www.baidu.com
Path: /
Scheme: http
Host: aa.cn
Path: /nha
说明:代码里面首先把中文都变成空格了,防止中文与英文网址在一起被错误识别,因为中文也是可以做网址的。例如“百度aaa.com”,如果不将中文替换成空格,则识别的网址为“百度aaa.com”,替换成空格后,则识别的网址为“aaa.com”。