static private String chooseSegment(String ns) {
    int off = ns.indexOf('#');
    if (off >= 0) {
      String segment = ns.substring(off + 1).toLowerCase();
      if (Naming.isNcname(segment))
        return segment;
    }
    else
      off = ns.length();
    for (;;) {
      int i = ns.lastIndexOf('/', off - 1);
      if (i < 0 || (i > 0 && ns.charAt(i - 1) == '/'))
        break;
      String segment = ns.substring(i + 1, off).toLowerCase();
      if (segmentOk(segment))
        return segment;
      off = i;
    }
    off = ns.indexOf(':');
    if (off >= 0) {
      String segment = ns.substring(off + 1).toLowerCase();
      if (segmentOk(segment))
        return segment;
    }
    return null;
  }