11

我使用以下内容从 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. 我究竟做错了什么?

4

7 回答 7

13

使用 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

于 2014-01-14T22:57:09.273 回答
8

通过 REGEX 获得主机是相当复杂或不可能的,因为 TLD 不遵守简单的规则,而是由 ICANN 提供并及时更改。

您应该使用 JAVA 库提供的功能,如下所示:

URL myUrl = new URL(urlString);
myUrl.getHost();
于 2011-08-27T21:55:13.777 回答
4

This is 2013 and solution I found is straight forward:

System.out.println(InternetDomainName.fromLenient(uriHost).topPrivateDomain().name());
于 2013-11-09T15:04:06.650 回答
3

它要简单得多:

  try {
        String domainName = new URL("http://www.zoyanailpolish.blogspot.com/some/long/link").getHost();

        String[] levels = domainName.split("\\.");
        if (levels.length > 1)
        {
            domainName = levels[levels.length - 2] + "." + levels[levels.length - 1];
        }

        // now value of domainName variable is blogspot.com
    } catch (Exception e) {}
于 2015-12-25T21:16:12.223 回答
2

正如 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

实施细节由您决定。

于 2011-08-27T22:10:32.157 回答
1

您看到的原因是您的正则表达式仅找到以“ww”开头zoyanailpolish.blogspot.com的字符串。您要问的是,除了删除所有以 'ww' 开头的字符串外,它还应该适用于以 'zoyanailpolish' (?) 开头的字符串。在这种情况下,使用正则表达式这将删除任何以“ww”或“z”或“a”开头的单词。根据您的确切需要对其进行自定义。String regex = "^((ww|z|a)[a-zA-Z0-9-]{0,}\\.)";

于 2011-08-27T21:24:04.870 回答
1
InternetDomainName.from("test.blogspot.com").topPrivateDomain() -> test.blogspot.com

这在我的情况下效果更好:

InternetDomainName.from("test.blogspot.com").topDomainUnderRegistrySuffix() -> blogspot.com

详情: https ://github.com/google/guava/wiki/InternetDomainNameExplained

于 2019-05-17T10:56:45.220 回答