java取得URL頂級域名
阿新 • • 發佈:2019-02-12
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/
正則表示式最後加上 .* 即可.
如要取完整域名,