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主域名 作者:anotherbug 日期:2008-04-11 11:55:49 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/ 正则表达式最后加上 .* 即可. 如要取完整域名, 1 Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); |
JAVA正则取URL主域名
最新推荐文章于 2024-07-27 04:45:29 发布