Regular Expressions using Python

Regular expressions are a set of characters called patterns that are used to find a substring in a given string. Simply put, this is a technique used to detect substrings in an input string. In this article, I’ll walk you through a tutorial on regular expressions in Python.

What are Regular Expressions?

Let’s understand the concept of regular expressions from an example, suppose you have a data that contains the reviews of customers and you want to extract emojis from this data because they can act as a good predictor about the sentiments of customers.

Also, Read – Python Projects with Source Code: Solved and Explained.

Let’s understand how the concept of regular expression works. Regular Expressions are used in the applications of natural language processing also, for example, virtual assistants like Siri, Google Now uses information retrieval systems to provide you with better results as per your query.

For example, you ask a virtual assistant to call a person, it will not search the internet for that query instead, it will identify the phrase as “calling” and then find the person you want to call. This is how regular expressions work.

Regular Expressions using Python

The regular expression is a very useful technique for dealing with text data because it helps to clean up and manage text data in a better way. Now let’s see how to work with regular expressions using Python. I’ll import the re module in Python first and see how to search for a specific word in a sentence:

import re
string= 'Hi, I am Aman Kharwal, I hope you are enjoying learning with me.'
re.search('Aman',string)
<_sre.SRE_Match object; span=(9, 13), match='Aman'>

Now let’s see how to find a date from a URL:

url = "https://thecleverprogrammer.com/2020/11/15/machine-learning-projects/"
date_regex='/(\d{4})/(\d{1,2})/(\d{1,2})'
print(re.findall(date_regex,url))
[('2020', '11', '15')]

You can create a regular expression that can match complex patterns by using special characters that not only match characters but define a rule. Let’s see how to find specific keywords in a multilinear paragraph:

['If', 'If']

I hope you liked this article on how to use the concept of regular expression using Python. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1433

Leave a Reply