-4

Possible Duplicate:
Regex to match URL

Given a String, I want to know whether it represents a URL or not and get the website name, which is the "whatever". For example, given "http://google.com.sg" or "http://google.com.sg/", I want to return String "google.com.sg".

Is there a neat way of doing this in Java?

Community
  • 1
  • 1
xiangxin
  • 409
  • 6
  • 18

2 Answers2

5

There are a number of ways of doing this, but a simple regular expression is quite error-prone. Best thing to do is to feed it to an existing parser and then use methods to pull out the bits that you need, for example

import java.net.URL;
...
final URL url = new URL("http://google.com.sg/");
final String host = url.getHost();
0

If you do want a regular expression, here is one:

    String foo = "http://google.com";
    String bar = foo.replaceAll("^http://", "");

    if (bar.length() != foo.length()) {
        System.out.println("Url: " + bar);
    } else {
        System.out.println("Not Url: " + foo);
    }
Mason Bryant
  • 1,372
  • 14
  • 23