30 Days Of Python πŸ‘¨β€πŸ’» - Day 19 - Regular Expressions

This article is a part of a 30 day Python challenge series. You can find the links to all the previous posts of this series here,
Regular Expressions (Regex/RegExp) is a powerful programming concept and is universal across all programming languages, but is often found to be confusing and hard to interpret, mainly by beginners. Regular Expressions are a sequence of character patterns used for efficiently searching strings. They offer a wide array of use cases when dealing with texts such as searching, validation or replacing texts.
 
Today I explored how to use regex in Python.
 
From my prior experience in writing JavaScript programs, I am already familiar with regular expressions. Also, there are tons of amazing resources available out there on the web about regular expressions. My intention today was to check out the syntax and method of using them in Python as knowing how to use regular expressions in Python will come in very handy when building projects in the upcoming days. So I compiled together some great resources related to regex in this post along with some practical coding exercises which I can use as a reference in future. It might help any enthusiast as well. There is no need to memorize each and every regex rule as they can always be Googled based on the requirement and most common regex patterns are readily available so we most of the time don’t need to create complex regex patterns ourselves.
 
However, having knowledge of how to read regex patterns is a great skill to have and it helps in understanding what a pattern is doing basically.
 
Here are some cool regex resources specific to Python
To practice and test regular expressions Regex101 is a great learning playground. It also helps in generating the equivalent Python regexp pattern as well
 

Regex methods in Python

 
To use regular expressions in Python, a built-in module re needs to be imported. This module comes with several methods for using regex.
 
Here is a great resource that lists all the regex methods that Python provides along with their use-cases.
 
Code Exercises
 
Let’s try out building some code to test out various practical use cases of regex in building Python applications.
 
Password Validator
  1. # Prompts user to enter a password and validates it  
  2. # Criteria:  
  3. # Min 8 characters  
  4. # Only alphabets, numbers and @$!%*?& allowed  
  5. # should have atleast 1 uppercase character  
  6. # should have atleat 1 lowercase character  
  7. # should have atleast 1 special character  
  8. # should have atleast 1 number  
  9. import re  
  10.   
  11. def password_checker():  
  12.     password = input('Please enter a password')  
  13.     password_pattern = re.compile(  
  14.         r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"  
  15.     )  
  16.     result = re.fullmatch(password_pattern, password)  
  17.     if result:  
  18.         print('Valid password')  
  19.     else:  
  20.         print('Invalid password')  
  21.   
  22. password_checker()  
Note
The above code can be made more interactive using a switch statement to check for conditions separately and displaying individual errors if any condition fails. If the above regex looks confusing, try copying it to regex101. It will breakdown the regex into chunks with explanations.
 
I prefer using the compile method to store the regex pattern as a reference which can be used later on. It returns a regex object.
 
The r before the regex string tells the Python interpreter that it is a raw string. With raw strings, there is no need for escaping characters.
 
Extract numbers from a string,
  1. # Program to extract numbers from a string  
  2.   
  3. import re  
  4.   
  5. string = 'Python was introduced in 1992. This is year 2020.'  
  6. pattern = '\d+'  
  7.   
  8. result = re.findall(pattern, string)  
  9. print(result) # ['1992', '2020']  
These are some basic examples of how regex can be used in Python.
 
Here are some good articles for more in-depth information on regex in Python
  • https://www.programiz.com/python-programming/regex
  • https://realpython.com/regex-python/
  • https://github.com/ziishaned/learn-regex (My personal favourite)
That’s all for today. Tomorrow I will be digging into testing techniques in Python. I am pretty excited about that.
 
Have a great one!


Recommended Free Ebook
Similar Articles