tags:

views:

155

answers:

2

Hi,

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

Thanks

+4  A: 

A very sneaky way is to do:

try {
    new java.net.URI(myUrl);
} catch(MalformedURLException e) {
    // url badly formed
}
Finbarr
I'd advise against using the URL class (see my answer below for URI) - it does a network lookup to resolve server names.
dplass
I actually meant to use the `URI` class, thanks for pointing this out.
Finbarr
Thanks for fixing the example.
dplass
+7  A: 

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