see
see

Reputation: 65

How to validate the URL using regex in Java?

I need to check if an URL is valid or not. The URL should contain some subdirectories like as:

example.com/test/test1/example/a.html

The URL should contain subdirectories test, test1 and example. How can I check if the URL is valid using regex in Java?

Upvotes: 1

Views: 3933

Answers (4)

Dubas
Dubas

Reputation: 2876

This question is answered here using regular expressions: Regular expression to match URLs in Java

But you can use the library Apache Commons Validators to use some tested validators instead to write your own.

Here is the library: http://commons.apache.org/validator/

And here the javadoc of the URL Validator. http://commons.apache.org/validator/apidocs/org/apache/commons/validator/UrlValidator.html

Upvotes: 0

limc
limc

Reputation: 40160

Since you want to do in regex, how about this...

Pattern p = Pattern.compile("example\\.com/test/test1/example/[\\w\\W]*");

System.out.println("OK: " + p.matcher("example.com/test/test1/example/a.html").find());
System.out.println("KO: " + p.matcher("example.com/test/test2/example/a.html").find());

Upvotes: 1

Bolo
Bolo

Reputation: 11690

You can simply pass your URL as an argument to the java.net.URL(String) constructor and check if the constructor throws java.net.MalformedURLException.

EDIT If, however, you simply want to check if a given string contains a given substring, use the String.contains(CharSequence) method. For example:

String url = "example.com/test/test1/example/a.html";
if (url.contains("/test/test1/")) {
    // ...
}

Upvotes: 0

dave
dave

Reputation: 12806

String url = "example.com/test/test1/example/a.html";
List<String> parts = Arrays.asList(url.split("/"));
return (parts.contains("test") && parts.contains("test1") && parts.contains("example"));

Upvotes: 2

Related Questions