Extract main domain name from a given url

domain-name, java, regex, url

Solution

As suggested by BalusC and others the most practical solution would be to get a list of TLDs (see this list), save them to a file, load them and then determine what TLD is being used by a given url String. From there on you could constitute the main domain name as follows:

    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

The implementation details are left up to you.

Problem

I used the following to extract the domain from a url: (They are test cases) ``` 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, ""); } ``` I can get the following results: ``` google.com hopperspot.com socialrating.it blogspot.com xtop10.net zoyanailpolish.blogspot.com ``` The first four cases are good. The last one is not good. What I want is: `blogspot.com` for the last one, but it gives `zoyanailpolish.blogspot.com`. What am I doing wrong?

Original source

Related problems