3

Does anyone know how to validate the format of a url in Java using regex?

Thanks

3
  • See also this question: stackoverflow.com/questions/27745/getting-parts-of-a-url-regex Commented Jun 7, 2010 at 20:45
  • Use regex. Don't use the classes shared below. They may open network connections. Commented Nov 24, 2011 at 4:56
  • @MikeNereson that's incorrect. java.net.URI will never accesses the network, it's the best way to validate URIs in Java. The equals() and hadhCode() methods of java.net.URL try to access the network, that's correct, but the java.net.URL constructor most likely won't. Commented May 11, 2012 at 21:54

2 Answers 2

7

A very sneaky way is to do:

try {
    new java.net.URI(myUrl);
} catch(URISyntaxException e) {
    // url badly formed
}
Sign up to request clarification or add additional context in comments.

5 Comments

I'd advise against using the URL class (see my answer below for URI) - it does a network lookup to resolve server names.
I actually meant to use the URI class, thanks for pointing this out.
Thanks for fixing the example.
The java.net.URI constructor throws a URISyntaxException not a MalformedURLException. At least on the version of Java on Android!
Firstly, it should be URISyntaxException and not MalformedURLException. And second, using exceptions for normal flow control is not a good practice. Additionally, if you don't intend to use the object returned by new java.net.URI(myUrl), then better avoid the invocation whatsoever. Checking the validity of a URI calls for a URIValidator class which should - to the best of my knowledge - make use of regex (which I'm still looking for around the net. I'll let you know as soon as I find something).
7

You might be better off using the URI class in Java: http://java.sun.com/j2se/1.5.0/docs/api/java/net/URI.html

It will throw an exception in the constructor if it doesn't parse correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.