Python - Extract URL from Text


URL extraction is achieved from a text file by using regular expression. The expression fetches the text wherever it matches the pattern. Only the re module is used for this purpose.


We can take a input file containig some URLs and process it thorugh the following program to extract the URLs. The findall()function is used to find all instances matching with the regular expression.

Inout File

Shown is the input file below. Which contains teo URLs.

Now a days you can learn almost anything by just visiting But if you are completely new to computers or internet then first you need to leanr those fundamentals. Next
you can visit a good e-learning site like - to learn further on a variety of subjects.

Now, when we take the above input file and process it through the following program we get the required output whihc gives only the URLs extracted from the file.

import re
with open("path\url_example.txt") as file:
        for line in file:
            urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', line)

When we run the above program we get the following output −


Useful Video Courses


Python Online Training

187 Lectures 17.5 hours

Malhar Lathkar


Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty


Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official


Python with Data Science

Best Seller

75 Lectures 13 hours

Eduonix Learning Solutions


Python 3 from scratch to become a developer in demand

Best Seller

70 Lectures 8.5 hours

Lets Kode It


Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

Abhilash Nelson