VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-an-url-is-valid-or-not-using-regular-expression/

⇱ Check if an URL is valid or not using Regular Expression - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if an URL is valid or not using Regular Expression

Last Updated : 15 Jul, 2025

Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.
Examples : 

Input : str = "https://www.geeksforgeeks.org/" 
Output : Yes 
Explanation : 
The above URL is a valid URL.
Input : str = "https:// www.geeksforgeeks.org/" 
Output : No 
Explanation : 
Note that there is a space after https://, hence the URL is invalid. 
 

Approach : 
An approach using java.net.url class to validate a URL is discussed in the previous post. 
Here the idea is to use Regular Expression to validate a URL. 

  • Get the URL.
  • Create a regular expression to check the valid URL as mentioned below:

regex = "((http|https)://)(www.)?" 
+ "[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]" 
+ "{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)"
 

  • The URL must start with either http or https and
  • then followed by :// and
  • then it must contain www. and
  • then followed by subdomain of length (2, 256) and
  • last part contains top level domain like .com, .org etc.
  • Match the given URL with the regular expression. In Java, this can be done by using Pattern.matcher().
  • Return true if the URL matches with the given regular expression, else return false.


Below is the implementation of the above approach:
 


Output: 
Yes

 

Time Complexity: O (N) 
Auxiliary Space: O (1)

Comment