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/
正则表达式最后加上 .* 即可.
如要取完整域名,
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/
正则表达式最后加上 .* 即可.
如要取完整域名,
本文介绍了一种使用JAVA正则表达式来精确匹配URL的方法,特别是如何抽取URL中的主域名部分,例如从'http://anotherbug.blog.chinajavaworld.com/entry/4545/0/'中提取'chinajavaworld.com'。
1244

被折叠的 条评论
为什么被折叠?



