Q:

Python program to print URL from a string

0

Example:

Input:
"learn python programming at https://www.includehelp.com/"

Output:
https://www.includehelp.com/

Python program to print URL using string

We will find the URL from the string using the regular expression which is made to accept URLs from the given strings.

We will use the findall() method from python's RE library.

Syntax:

findall(regex, string)

Regular expression to find the URL of a string

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

This large expression checks for all possible combinations of the URL. starting from character followed by http_: … and then . followed by the top level domain.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print URL from the string

# Python program to print URL from a string
import re

# Getting strings as input from the user 
myStr = input('Enter string : ')

# Finding all URLS from the string 
urlRegex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))"

allUrls = re.findall(urlRegex,myStr)	

print("All URLs are ", [url[0] for url in allUrls])

Output:

Enter string : Learn Pythoat https://www.includehelp.com
All URLs are  ['https://www.includehelp.com']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now