• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Python RegEx | Regular Expression Tutorial with Examples

Aniruddha Chaudhari/8610/0
CodePython

The RegEx of the Regular Expression is actually a sequene of charaters that is used for searching or pattern matching.

Python has module re for matching search patterns. It comes inbuilt with Python installation. You just need to import and use it.

Let’s see this simple Python regex example.

Search if there is at least two consecutive English uppercase letters.

import re

print(bool(re.search("[A-Z]{2}", "cdABp")))
#True

print(bool(re.search("[A-Z]{2}", "1Z")))
#False

print(bool(re.search("[A-Z]{2}", "A1P")))
#False

Table of Contents

  • RegEx Functions
  • RegEx Sets
  • Special RegEx Characters
  • Python RegEx Coding Examples
    • 1. search() function
    • 2. findall() function
    • 3. split() function
    • 4. sub() function
  • Python RegEx Questions asked in Interview

RegEx Functions

Python re modules offer the following functions for pattern matching. You can use them for different purposes.

FunctionDescription
searchreturns match object if match found
findallreturns list of all the matches from the given string
splitreturns list of string where it has been split for each match
subreturns string by replacing all the matches

RegEx Sets

Just like the English uppercase letters example, we have seen above, there are other different sets you can use in Python regex.

SetMatching Characters
[A-Z]set which returns a match for any character between ‘A’ to ‘Z’ (uppercase letters)
[a-z]set which returns a match for any character between ‘a’ to ‘z’ (lowercase letters)
[0-9]set which returns a match for any character between ‘0’ to ‘9’ (numeric number)
[A-Za-z]set which returns a match for any alphabetic character (includes both uppercase and lowercase letters)
[A-Za-z0-9]set which returns a match for any alphabetic or numeric character (includes both uppercase, lowercase letters and numbers)
[apx]set which returns match if one of the character (‘a’, ‘p’, ‘x’) are present

Special RegEx Characters

CharacterDescriptionExample
[]to define set of characters[A-Z]
match all the uppercase letters
{}to match the exact number of characters{2}
match only two characters
^to check the prefix (starts with)“^CSE”
string start with “CSE”
$to check the postfix (ends with)“stack$”
string ends with “stack”
*to match zero or more occurrencespos*
match the string contains “po” followed by zero or more “s” characters
+to match one or more occurrencespos+
match the string contains “po” followed by one or more “s” characters
|or operation“CSE|stack”
match string contains either “CSE” or “stack”:
()form a group
.to match any character (except newline character)“CS..ack”
match the string containing “CS” followed by any other two characters and then “ack”
\to match special sequence“\d”
match all digit characters

Python RegEx Coding Examples

1. search() function

Search the first occurrence of “ing” in the given string.

import re
match_obj = re.search("ing", "CSEstack Programming Portal")
print(match_obj.start())
print(match_obj.end())

Output

17
20

Explanation

  • The search function returns a match object.
  • If no match found, it returns the NoneType object.
  • You can use the start() and end() methods of match object to get the start and end index of the matching pattern.
  • You can also convert a match object into the True/False Boolean values using bool() method. Return True if match found, else False.

2. findall() function

Find all the matching which contains character “r” and followed by two any other characters.

import re
match_list = re.findall("r..", "Programming Portal- Keep Coding")
print(match_list)

Output

['rog', 'ram', 'rta']

Explanation

  • Method findall() returns Python list object. So, you can perform any operations on matches that we do with the Python list.

3. split() function

Split the given string by occurrence of character ‘a’ or ‘g’.

import re
match_list = re.split("a|g", "CSEstack Programming Portal")
print(match_list)

Output

['CSEst', 'ck Pro', 'r', 'mmin', ' Port', 'l']

Explanation

  • Like findall(), split() method also returns Python list.

4. sub() function

Replace all the occurrences of substring “cse” with “CSE”

import re
match_string = re.sub("cse", "CSE", "Learn coding from csestack.")
print(match_string)

Output

Learn programming from CSEstack.

Explanation

  • Method sub(), returns the Python string.

These are the simple examples to demonstarte different reguylar explression and methods.

Regular expressions are extremely useful in different fields like data analytics or projects for pattern matching.

Python RegEx Questions asked in Interview

Here are some of the examples asked in coding interviews. Take them as coding exercise and practice solving them.

  • Write a regular expression to check the valid IP addresses.
    (This was asked in Juniper coding interview.)
  • Based on the given criteria, find all the Visa, MasterCard and American credit cards.
    (This was asked in Byju’s coding interview.)
  • Find all the PAN card numbers from the given paragraph.
    (This was asked in the BrightMoney coding interview.)

This is all about Regular Expression in Python (Python RegEx). Hope you find this tutorial useful for your learning.

Python Interview Questions eBook

Pythonregex
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard