我使用以下方法从 url 中提取域:(它们是测试用例)
String regex = "^(ww[a-zA-Z0-9-]{0,}\\.)";
ArrayList<String> cases = new ArrayList<String>();
cases.add("www.google.com");
cases.add("ww.socialrating.it");
cases.add("www-01.hopperspot.com");
cases.add("wwwsupernatural-brasil.blogspot.com");
cases.add("xtop10.net");
cases.add("zoyanailpolish.blogspot.com");
for (String t : cases) {
String res = t.replaceAll(regex, "");
}
我可以得到如下结果:
google.com
hopperspot.com
socialrating.it
blogspot.com
xtop10.net
zoyanailpolish.blogspot.com
前四种情况都不错。最后一个不好。我想要的是:blogspot.com
为最后一个,但它给出了 zoyanailpolish.blogspot.com
。我做错了什么?
最佳答案
使用Guava库,我们可以轻松获取域名:
InternetDomainName.from(tld).topPrivateDomain()
更多详细信息请引用 API 链接
https://google.github.io/guava/releases/14.0/api/docs/
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/net/InternetDomainName.html
关于java - 从给定的 url 中提取主域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7217271/