-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?

3
  • 2
    What have you tried? Just search for Java+Regex, you should find something Commented Jan 30, 2013 at 21:06
  • please show us whatever you have tried .. :) Commented Jan 30, 2013 at 21:06
  • If this isn't a duplicate, I don't know what is. Try [regex] match URL or similar. Commented Jan 30, 2013 at 21:06

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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);
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.