Program to check whether the given URL is valid or not using regex

by | Dec 26, 2020 | Python Programs

Home » Python » Python Programs » Program to check whether the given URL is valid or not using regex

Introduction

The task is to check whether the given URL is valid or not using regex expression.

check whether the given URL is valid

Program

import re
 
def check_url(ip_url):
# Regular expression for URL
    re_exp = ("((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" +
             "{2,256}\\.[a-z]" + "{2,6}\\b([-a-zA-Z0-9@:%" + "._\\+~#?&//=]*)")
    exp = re.compile(re_exp)
    if (ip_url == None):
        print("Input string is empty")
    if(re.search(exp, ip_url)):
        print("Input URL is valid!")
    else:
        print("Input URL is invalid!")
ip_url = input("Enter the string: ")
check_url(ip_url)

Output

check whether the given URL is valid Output

Explanation

In the above python code we have passed the regex expression and string to search() method and checked whether the input URL matches the expression pattern. If the pattern is matched, the URL is valid else the URL is invalid.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author