我使用以下代码从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。我做错了什么?
发布于 2011-08-28 06:10:32
正如BalusC和其他人所建议的,最实用的解决方案是获取TLD列表(参见此list),将它们保存到文件中,加载它们,然后确定给定的url字符串正在使用哪个TLD。从那时起,您可以按如下方式构成主域名:
String url = "zoyanailpolish.blogspot.com";
String tld = findTLD( url ); // To be implemented. Add to helper class ?
url = url.replace( "." + tld,"");
int pos = url.lastIndexOf('.');
String mainDomain = "";
if (pos > 0 && pos < url.length() - 1) {
mainDomain = url.substring(pos + 1) + "." + tld;
}
// else: Main domain name comes out empty具体实现细节由您决定。
发布于 2014-01-15 06:57:09
使用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
发布于 2011-08-28 05:55:14
通过REGEX获取主机是相当复杂或不可能的,因为TLD不遵守简单的规则,而是由ICANN提供的,并且会随着时间的变化而变化。
您应该使用JAVA库提供的功能,如下所示:
URL myUrl = new URL(urlString);
myUrl.getHost();https://stackoverflow.com/questions/7217271
复制相似问题