Open In App

Parsing and Processing URL using Python – Regex

Prerequisite: Regular Expression in Python

URL or Uniform Resource Locator consists of many information parts, such as the domain name, path, port number etc. Any URL can be processed and parsed using Regular Expression. So for using Regular Expression we have to use re library in Python.



Example:

URL: https://www.geeksforgeeks.org/courses
When we parse the above URL then we can find

Hostname: geeksforgeeks.com
Protocol: https

We are using re.findall( ) function of re library for searching the required pattern in the URL.



Syntax: re.findall(regex, string)  

Return: all non-overlapping matches of pattern in string, as a list of strings. 

Now, let’s see the examples:

Example 1: In this Example, we will be extracting the protocol and the hostname from the given URL.

Meta characters Used:

Code:




# import library
import re  
  
# url link
  
# finding the protocol 
obj1 = re.findall('(\w+)://',
                  s)
print(obj1)
  
# finding the hostname which may
# contain dash or dots
obj2 = re.findall('://www.([\w\-\.]+)'
                  s)
print(obj2)

Output:

['https']
['geeksforgeeks.org']

Example 2: If the URL is of a different type such as ‘file://localhost:4040/zip_file‘, with the port number along with it, then to extract the port number, as it is optional we will use the ‘?’ notation. Here the port number ‘4040′ occurs after the ‘:’ sign. Therefore, as it is a digit (:(\d+)) is used. To make it optional as all URLs do not end with host number, this syntax is used ‘(:(\d+))?’.

Meta characters Used:

Code:




# import library
import re  
  
# url link
  
# finding the file capture group
obj1 = re.findall('(\w+)://', s)  
print(obj1)
  
# finding the hostname which may 
# contain dash or dots
obj2 = re.findall('://([\w\-\.]+)', s)
print(obj2)
  
# finding the hostname which may 
# contain dash or dots or port
# number
obj3 = re.findall('://([\w\-\.]+)(:(\d+))?', s)
print(obj3)

Output:

['file']
['localhost']
[('localhost', ':4040', '4040')]

Example 3: For a general URL, this can be used, where the path elements can also be constructed.




# import library
import re
  
# url
  
# searching for all capture groups
obj = re.findall('(\w+)://([\w\-\.]+)/(\w+).(\w+)',
                 s)
  
print(obj)

Output:

[('http', 'www.example.com', 'index', 'html')]

Article Tags :