0

I need to parse url in my java code and get the domain. I wrote the following code:

    static String domain(URL url) {
        String host = url.getHost();
        int i = host.lastIndexOf('.');
                if(i == -1){

                    return "Not domain";
                }
                if (i ==0 ){

                    return "Not domain";
                }
                String domain; 
                i = host.lastIndexOf('.', i - 1);
                if (i == -1) {
                    domain = host;
                }
                else {
                    domain = host.substring(i + 1, host.length());
                }
    }

This code parses domains like example.com

But how can my code parse domains like exmaple.co.ir , subdomains.example.co.ir and the others extensions like co.uk, org.ir and so on.

EDIT

my url is http//blog.example.co.ir/index.php or http//blog.example.co.uk/something.html

my goal is to print:

example.co.ir and example.co.uk

Amir
  • 1,009
  • 1
  • 9
  • 11
  • I am confused by your question. getHost() should return the host - what am I missing? – Scary Wombat Jan 21 '14 at 07:03
  • Refer to this **[answer](http://stackoverflow.com/a/9608008/500725)** – Siva Charan Jan 21 '14 at 07:04
  • @user2310289 My code gets a url (http://a.b.c.example.co.ir/index/news/....) then parses it to "a.b.c.example.co.ir"! Finally, it sends out the domain "example.co.ir" – Amir Jan 22 '14 at 06:42

2 Answers2

0

I believe this work for any kind of URL(in correct URL format)

domain= host.split("/")[2];

Note:

split("/") will create an array from the String, for example:

String host="http//blog.example.co.ir/index.php";

host.split("/") will give you array of String: [http, ,blog.example.co.ir, index.php]

And your desired output is at index 2

Baby
  • 5,062
  • 3
  • 30
  • 52
0

The problem is that your parsing code is limited to domains with just one dot. You can use regular expressions or recursive parsing to solve this problem. This is one way of approaching this problem.

user6123723
  • 10,546
  • 18
  • 67
  • 109