![]() |
VOOZH | about |
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.
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.
Below is the implementation of the above approach:
Yes
Time Complexity: O (N)
Auxiliary Space: O (1)