Skip to content
Related Articles
Open in App
Not now

Related Articles

Check if an URL is valid or not using Regular Expression

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 07 Dec, 2022
Improve Article
Save Article

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:
 

C++




// C++ program to validate URL
// using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate URL
// using regular expression
bool isValidURL(string url)
{
 
  // Regex to check valid URL
  const regex pattern("((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)");
 
  // If the URL
  // is empty return false
  if (url.empty())
  {
     return false;
  }
 
  // Return true if the URL
  // matched the ReGex
  if(regex_match(url, pattern))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
// Driver Code
int main()
{
  string url = "https://www.geeksforgeeks.org";
 
  if (isValidURL(url))
  {
    cout << "YES";
  }
  else
  {
    cout << "NO";
  }
  return 0;
}
 
// This code is contributed by yuvraj_chandra

Java




// Java program to check URL is valid or not
// using Regular Expression
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate URL
    // using regular expression
    public static boolean
    isValidURL(String url)
    {
        // Regex to check valid URL
        String regex = "((http|https)://)(www.)?"
              + "[a-zA-Z0-9@:%._\\+~#?&//=]"
              + "{2,256}\\.[a-z]"
              + "{2,6}\\b([-a-zA-Z0-9@:%"
              + "._\\+~#?&//=]*)";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (url == null) {
            return false;
        }
 
        // Find match between given string
        // and regular expression
        // using Pattern.matcher()
        Matcher m = p.matcher(url);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver code
    public static void main(String args[])
    {
        String url
            = "https://www.geeksforgeeks.org";
        if (isValidURL(url) == true) {
            System.out.println("Yes");
        }
        else
            System.out.println("NO");
    }
}

Python3




# Python3 program to check
# URL is valid or not
# using regular expression
import re
 
# Function to validate URL
# using regular expression
def isValidURL(str):
 
    # Regex to check valid URL
    regex = ("((http|https)://)(www.)?" +
             "[a-zA-Z0-9@:%._\\+~#?&//=]" +
             "{2,256}\\.[a-z]" +
             "{2,6}\\b([-a-zA-Z0-9@:%" +
             "._\\+~#?&//=]*)")
     
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
# Test Case 1:
 
if(isValidURL(url) == True):
    print("Yes")
else:
    print("No")
 
# This code is contributed by avanitrachhadiya2155

C#




//  C#  program to check URL is valid or not
//using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG
{
 
  // Main Method
  static void Main(string[] args)
  {
 
    // Input strings to Match
    // Valid URL
    string[] str={"https://www.geeksforgeeks.org"};
    foreach(string s in str) {
      Console.WriteLine( isValidURL(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
  // method containing the regex
  public static bool isValidURL(string str)
  {
    string strRegex = @"((http|https)://)(www.)?" +
      "[a-zA-Z0-9@:%._\\+~#?&//=]" +
      "{2,256}\\.[a-z]" +
      "{2,6}\\b([-a-zA-Z0-9@:%" +
      "._\\+~#?&//=]*)";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
      return (true);
    else
      return (false);
  }
}
 
// This code is contributed by Rahul Chauhan

Javascript




function isValidURL(str) {
   if(/^(http(s):\/\/.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/g.test(str)) {
        console.log('YES');
    } else {
        console.log('NO');
    }
}
  
 
// This code is contributed by Rahul Chauhan

Output: 

Yes

 

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!