chn*_*net 10 java regex url domain-name
我使用以下内容从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, "");
}
Run Code Online (Sandbox Code Playgroud)
我可以得到以下结果:
google.com
hopperspot.com
socialrating.it
blogspot.com
xtop10.net
zoyanailpolish.blogspot.com
Run Code Online (Sandbox Code Playgroud)
前四个案例都很好.最后一个不好.我想要的是:blogspot.com对于最后一个,但它给出了zoyanailpolish.blogspot.com.我究竟做错了什么?
小智 11
使用Guava库,我们可以轻松获得域名:
InternetDomainName.from(tld).topPrivateDomain()
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅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
通过REGEX获取主机非常复杂或不可能,因为TLD不遵守简单的规则,但由ICANN提供并及时更改.
您应该使用JAVA库提供的功能,如下所示:
URL myUrl = new URL(urlString);
myUrl.getHost();
Run Code Online (Sandbox Code Playgroud)
这是 2013 年,我找到的解决方案很简单:
System.out.println(InternetDomainName.fromLenient(uriHost).topPrivateDomain().name());
Run Code Online (Sandbox Code Playgroud)
正如 BalusC 和其他人所建议的,最实用的解决方案是获取 TLD 列表(请参阅此列表),将它们保存到文件中,加载它们,然后确定给定 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
Run Code Online (Sandbox Code Playgroud)
实施细节由您决定。
| 归档时间: |
|
| 查看次数: |
25932 次 |
| 最近记录: |