3

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

Thanks

GigaPr
  • 5,206
  • 15
  • 60
  • 77
  • See also this question: http://stackoverflow.com/questions/27745/getting-parts-of-a-url-regex – Pops Jun 07 '10 at 20:45
  • Use regex. Don't use the classes shared below. They may open network connections. – MikeNereson Nov 24 '11 at 04: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. – jcsahnwaldt Reinstate Monica May 11 '12 at 21:54

2 Answers2

7

A very sneaky way is to do:

try {
    new java.net.URI(myUrl);
} catch(URISyntaxException e) {
    // url badly formed
}
kldavis4
  • 2,177
  • 1
  • 22
  • 33
Finbarr
  • 31,350
  • 13
  • 63
  • 94
  • 3
    I'd advise against using the URL class (see my answer below for URI) - it does a network lookup to resolve server names. – dplass Jun 07 '10 at 20:41
  • I actually meant to use the `URI` class, thanks for pointing this out. – Finbarr Jun 07 '10 at 20:42
  • Thanks for fixing the example. – dplass Jun 07 '10 at 20:45
  • 3
    The java.net.URI constructor throws a URISyntaxException not a MalformedURLException. At least on the version of Java on Android! – Ben Clayton Feb 28 '11 at 14:36
  • 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). – Pantelis Sopasakis Aug 24 '12 at 17:33
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.

dplass
  • 1,463
  • 10
  • 20