The Wayback Machine - https://web.archive.org/web/20240907073947/https://www.geeksforgeeks.org/parsing-and-processing-url-using-python-regex/
Open In App

Parsing and Processing URL using Python – Regex

Last Updated : 02 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

  • Regular expression for extracting protocol group: ‘(\w+)://‘.
  • Regular expression for extracting hostname group: ‘://www.([\w\-\.]+)‘.

Meta characters Used:

  • \w: Matches any alphanumeric character, this is equivalent to the class [a-zA-Z0-9_].
  • +: One or more occurrences of previous characters.

Code:

Python3




# 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:

  • \d: Matches any decimal digit, this is equivalent to the set class [0-9].
  • +: One or more occurrences of previous characters.
  • ?: Matches zero or one occurrence.

Code:

Python3




# 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.

Python3




# 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')]


Similar Reads

NLP | Partial parsing with Regex
Defining a grammar to parse 3 phrase types. ChunkRule class that looks for an optional determiner followed by one or more nouns is used for noun phrases. To add an adjective to the front of a noun chunk, MergeRule class is used. Any IN word is simply chunked for the prepositional phrases. an optional modal word (such as should) followed by a verb i
2 min read
Point Processing in Image Processing using Python-OpenCV
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. Point processing in spatial domain All the
3 min read
Parsing and converting HTML documents to XML format using Python
In this article, we are going to see how to parse and convert HTML documents to XML format using Python. It can be done in these ways: Using Ixml module.Using Beautifulsoup module.Method 1: Using the Python lxml library In this approach, we will use Python's lxml library to parse the HTML document and write it to an encoded string representation of
3 min read
Command-Line Option and Argument Parsing using argparse in Python
Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module. Python Argparse ModuleThe 'argparse' module in Python hel
8 min read
How to Add URL Parameters to Django Template URL Tag?
When building a Django application, it's common to construct URLs dynamically, especially when dealing with views that require specific parameters. The Django template language provides the {% url %} template tag to create URLs by reversing the URL patterns defined in the urls.py file. This tag becomes especially useful when we need to pass additio
4 min read
Parsing XML with DOM APIs in Python
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as bel
2 min read
Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries
Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By buildin
4 min read
Parsing PDFs in Python with Tika
Apache Tika is a library that is used for document type detection and content extraction from various file formats. Using this, one can develop a universal type detector and content extractor to extract both structured text and metadata from different types of documents such as spreadsheets, text documents, images, PDF's, and even multimedia input
2 min read
Parsing DateTime strings containing microseconds in Python
Most of the applications require a precision of up to seconds but there are also some critical applications that require nanosecond precision, especially the ones which can perform extremely fast computations. It can help provide insights on certain factors related to time space for the application. Let us see how can we parse DateTime strings that
3 min read
JSON Parsing Errors in Python
JSON is a widely used format for exchanging data between systems and applications. Python provides built-in support for working with JSON data through its JSON module. However, JSON parsing errors can occur due to various reasons such as incorrect formatting, missing data, or data type mismatches. There are different JSON parsing errors that can oc
6 min read
XML parsing in Python
This article focuses on how one can parse a given XML file and extract some useful data out of it in a structured way. XML: XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable.That's why, the design goals of XML emphasize simplicity, generality, and usability
7 min read
Python | Swap Name and Date using Group Capturing in Regex
In this article, we will learn how to swap Name and Date for each item in a list using Group Capturing and Numeric Back-referencing feature in Regex . Capturing Group : Parentheses groups the regex between them and captures the text matched by the regex inside them into a numbered group i.e ([\w ]+) which can be reused with a numbered back-referenc
3 min read
Parsing tables and XML with BeautifulSoup
Scraping is a very essential skill that everybody should learn, It helps us to scrap data from a website or a file that can be used in another beautiful manner by the programmer. In this article, we will learn how to extract tables with beautiful soup and XML from a file. Here, we will scrap data using the Beautiful Soup Python Module. Perquisites:
4 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
The most occurring number in a string using Regex in python
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python. It is guaranteed that no two element have the same frequency Examples: Input :geek55of55geeks4abc3dr2 Output :55Input :abcd1def2high2bnasvd3vjhd44Output :2Approach:Extract all the numbers from a string str usi
2 min read
Name validation using IGNORECASE in Python Regex
In this article, we will learn about how to use Python Regex to validate name using IGNORECASE. re.IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It's passed as an optional argument to re.compile(). Let's consider a
2 min read
Categorize Password as Strong or Weak using Regex in Python
Given a password, we have to categorize it as a strong or weak one. There are some checks that need to be met to be a strong password. For a weak password, we need to return the reason for it to be weak. Conditions to be fulfilled are: Minimum 9 characters and maximum 20 characters.Cannot be a newline or a spaceThere should not be three or more rep
2 min read
How to check if a string starts with a substring using regex in Python?
Prerequisite: Regular Expression in Python Given a string str, the task is to check if a string starts with a given substring or not using regular expression in Python. Examples: Input: String: "geeks for geeks makes learning fun" Substring: "geeks" Output: True Input: String: "geeks for geeks makes learning fun" Substring: "makes" Output: FalseChe
3 min read
Converting a 10 digit phone number to US format using Regex in Python
Text preprocessing is one of the most important tasks in Natural Language Processing. You may want to extract number from a string. Writing a manual script for such processing task requires a lot of effort and at most times it is prone to errors. Keeping in view the importance of these preprocessing tasks, the concept of Regular Expression have bee
1 min read
How to check a valid regex string using Python?
A Regex (Regular Expression) is a sequence of characters used for defining a pattern. This pattern could be used for searching, replacing and other operations. Regex is extensively utilized in applications that require input validation, Password validation, Pattern Recognition, search and replace utilities (found in word processors) etc. This is du
6 min read
Python - Check if String Contain Only Defined Characters using Regex
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Explanation: The Input string only consists of charac
2 min read
BeautifulSoup - Parsing only section of a document
BeautifulSoup is a Python Module used to find specific website contents/tags from a scraped website which can be scraped by any module like requests or scrapy. Remember BeautifulSoup doesn't scrape a website but processes and displays the scraped contents by other modules in a readable form. So, to understand how we can scrape the data on a website
2 min read
Pandas | Parsing JSON Dataset
Parsing of JSON Dataset using pandas is much more convenient. Pandas allow you to convert a list of lists into a Dataframe and specify the column names separately. A JSON parser transforms a JSON text into another representation must accept all texts that conform to the JSON grammar. It may accept non-JSON forms or extensions. An implementation may
4 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
Python Regex - re.MatchObject.start() and re.MatchObject.end() functions
In this article, we are going to see re.MatchObject.start() and re.MatchObject.end() regex methods. re.MatchObject.start() This method returns the first index of the substring matched by group. Syntax: re.MatchObject.start([group]) Parameter: group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists b
2 min read
How to Remove repetitive characters from words of the given Pandas DataFrame using Regex?
Prerequisite: Regular Expression in Python In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex. Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular ex
2 min read
Replace values in Pandas dataframe using regex
While working with large sets of data, it often contains text data and in many cases, those texts are not pretty at all. The text is often in very messier form and we need to clean those data before we can do anything meaningful with that text data. Mostly the text corpus is so large that we cannot manually list out all the texts that we want to re
4 min read
How to validate an IP address using ReGex
Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address. Examples: Input: str = "203.120.223.13" Output: Valid IPv4 Input: str = "000.12.234.23.23" Output: Invalid IP Input: str = "2F33:12a
5 min read
Extract punctuation from the specified column of Dataframe using Regex
Prerequisite: Regular Expression in Python In this article, we will see how to extract punctuation used in the specified column of the Dataframe using Regex. Firstly, we are making regular expression that contains all the punctuation: [!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]* Then we are passing each row of specific column to re.findall() functi
2 min read
Extract date from a specified column of a given Pandas DataFrame using Regex
In this article, we will discuss how to extract only valid date from a specified column of a given Data Frame. The extracted date from the specified column should be in the form of 'mm-dd-yyyy'. Approach: In this article, we have used a regular expression to extract valid date from the specified column of the data frame. Here we used \b(1[0-2]|0[1-
2 min read
Article Tags :
Practice Tags :