It turns out that extracting second- and top-level domains is not a simple task, the primary difficulty being that in addition to the usual suspects (.com .org .net etc), there are the country suffixes (.uk .it .de etc) which need to be accounted for.

Regex alone has no way of handling this. http://publicsuffix.org/list/ contains a somewhat authoritative list of TLD and ccTLD that we can use.

Here follows a Java class which parses this list, builds a regex from it, and extracts out the the TLD and second-level domain from a hostname. You'll need to download the effective_tld_names.dat from http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1 and place it in the same directory as the Java class.

In my next post, I'll build a Lucene Tokenizer out of this, so it can be used in Lucene and Solr.

package org.supermind.solr.analysis;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class SecondLDExtractor {
  private StringBuilder sb = new StringBuilder();
  private Pattern pattern;
 
  public void init() {
    try {
      ArrayList<String> terms = new ArrayList<String>();
 
      BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("effective_tld_names.dat")));
      String s = null;
      while ((s = br.readLine()) != null) {
        s = s.trim();
        if (s.length() == 0 || s.startsWith("//") || s.startsWith("!")) continue;
        terms.add(s);
      }
      Collections.sort(terms, new StringLengthComparator());
      for(String t: terms) add(t);
      compile();
      br.close();
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }
 
  protected void add(String s) {
    s = s.replace(".", "\\.");
    s = "\\." + s;
    if (s.startsWith("*")) {
      s = s.replace("*", ".+");
      sb.append(s).append("|");
    } else {
      sb.append(s).append("|");
    }
  }
 
  public void compile() {
    if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
    sb.insert(0, "[^.]+?(");
    sb.append(")$");
    pattern = Pattern.compile(sb.toString());
    sb = null;
  }
 
  public String extract2LD(String host) {
    Matcher m = pattern.matcher(host);
    if (m.find()) {
      return m.group(0);
    }
    return null;
  }
 
  public String extractTLD(String host) {
    Matcher m = pattern.matcher(host);
    if (m.find()) {
      return m.group(1);
    }
    return null;
  }
 
  public static class StringLengthComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
      if (s1.length() > s2.length()) return -1;
      if (s1.length() < s2.length()) return 1;
      return 0;
    }
  }
}