Skip to content

All topics  /  Python

How To Get Url From String Using Python ?

Python ·

Hello Friends,

Now let's see example of how to find url from string in python. We will talk about extract url from string using the regular expression module of python. I am going to share with you how to extract url from string using python.

We can take a input file containig some URLs and process it thorugh the following program to extract the URLs.

Here i will give you simple example of how to extract url from string in python example, So let's see the below example:

Example


import re

  
def getUrl(string):

  
    # findall() has been used 
    # with valid conditions for urls in string
    regex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))"
    url = re.findall(regex,string)      
    return [x[0] for x in url]

      
string = 'Python Program List: /cat/python'
print(getUrl(string))

Output

/cat/python

It will help you....