java取得URL顶级域名

来源:互联网 发布:阅读器软件下载 编辑:程序博客网 时间:2024/04/29 03:43
String url = "http://anotherbug.blog.chinajavaworld.com/entry/4545/0/";
Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(url);
matcher.find();
System.out.println(matcher.group());



结果:
chinajavaworld.com

如果要得到 chinajavaworld.com/entry/4545/0/

正则表达式最后加上 .* 即可.




主要是判断后缀而后缀可能有
.com
.net
.cn
.org
.com.cn
.net.cn
.org.cn
.biz
.info
.cc
.tv
   
写出来就是
   
(?<=(?:://\w+\.)?)(?:\w+\.)(?:com\.cn|net\.cn|org\.cn|com|net|org|cn|biz|info|cc|tv)
   
测试
http://www.csdn.com/....
http://www.csdn.com.cn/....
ftp://www.csdn.com/....
www.csdn.com/...
等等
都能正确获取csdn.xxx(.xx)
   
注意:com\.cn|net\.cn|org\.cn   必须放在   com|net|org的前面   因为或选项是从左到右短路查询的   前面找到匹配后面的将被忽略.
    




JAVA正则取URL主域名


String url = "http://anotherbug.blog.chinajavaworld.com/entry/4545/0/";
Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(url);
matcher.find();
System.out.println(matcher.group());



结果:
chinajavaworld.com

如果要得到 chinajavaworld.com/entry/4545/0/

正则表达式最后加上 .* 即可.

如要取完整域名,
原创粉丝点击