Program to check whether the given string contains URL using Python

Introduction

In this section, the task is to find whether the string contains URL and if the condition is true, the URL is returned.

Program to check whether the given string contains URL

Program

import re




def ck_url(x):

# Regular expression for url

    re_equ = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"

    ck_url = re.findall(re_euq, x)

    if ck_url:

        return "The url in the string is : ",[i[0] for i in ck_url]

    else:

        return "No URL present!"

       

ip_str = input("Enter the string : ")

print(ck_url(ip_str))

 

Output 1:

Program to check whether the given string contains URL Output 1

Output 2:

Program to check whether the given string contains URL Output 2

Explanation

In the above python code, to check the URL in the string we have created a regular expression for URL and by using findall() in-built function we are checking the URL pattern in the input string. The findall() function scans the string from left to right and the value is returned.

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

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.