Fixed Top Ad (Local Preview)800x90 • Slot 6608427872

Regex in Python

1. Introduction to Python re Library

    1.1 🐍 What is re?
    1. Python has a built-in library called re for working with regular expressions. Because it is built into Python, we do not need to install anything extra. We can simply import it: import re
    1.2 What Can We Do with re?
    1. The re library provides functions to: 👉 Search text 👉 Validate patterns 👉 Extract matching text 👉 Split text using patterns 👉 Replace matching text 📌 Regex gives us the pattern. Python's re library helps us apply that pattern to text.

2. re.search()

    2.1 🔍 What is re.search()?
    1. re.search() searches for a pattern inside a given text. It returns: 👉 The first match object if the pattern is found 👉 None if the pattern is not found Syntax: re.search(pattern, text)
2.2 Search Match Object Methods
MethodMeaning
.group()Returns the matched text
.start()Returns starting index
.end()Returns ending index
.span()Returns start and end index as a tuple
Python Regex Search Function
Python Regex Search Function
    2.3 Example: Search Weight
    1. import reusr_txt = "I bought 12 kg of apples."weight_regex = r"\d+(?= kg)"match = re.search(weight_regex, usr_txt)if match:print("Weight:", match.group())print("Start index:", match.start())print("End index:", match.end())print("Span:", match.span()) else:print("No weight found.")Output: Weight: 12 Start index: 9 End index: 11 Span: (9, 11) 📌 re.search() finds the first matching pattern.

3. Named Groups

    3.1 🏷️ What is a Named Group?
    1. A named group gives a name to a capturing group. Syntax: (?P<name>...) This allows us to access matched text by name instead of group number.
    3.2 Example: Extract Date Parts
    1. import reusr_txt = "Date of today is 2026-07-10. I have 3 classes today."date_regex = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"match = re.search(date_regex, usr_txt)if match:print("Year:", match.group("year"))print("Month:", match.group("month"))print("Day:", match.group("day")) else:print("No date found.")Output: Year: 2026 Month: 07 Day: 10 📌 Named groups make extracted data easier to understand.
    3.3 Named Group vs Numbered Group
    1. Using numbered groups: match.group(1)match.group(2)match.group(3) Using named groups: match.group("year")match.group("month")match.group("day") 📌 Named groups are easier to read, especially in larger patterns.

4. re.findall()

    4.1 📋 What is re.findall()?
    1. re.findall() finds all non-overlapping matches of a pattern in a string. It returns a list. Syntax: re.findall(pattern, text)
    4.2 Example: Find All Weights
    1. import reusr_txt = "I bought 10 kg apple, 5 kg mango and 12 litre curd for salad."weight_regex = r"\d+(?= kg)"weights = re.findall(weight_regex, usr_txt)print("Weights found:", weights)Output: Weights found: ['10', '5'] 📌 12 litre is not matched because the regex only looks for numbers followed by kg. 📌 re.findall() gives all matching results as a list.
Python Regex: search vs findall
Python Regex: search vs findall

5. re.split()

    5.1 ✂️ What is re.split()?
    1. re.split() splits a string wherever a pattern is found. It returns a list of substrings. Syntax: re.split(pattern, text)
Python Regex: split function
Python Regex: split function
    5.2 Example: Split by Weight Values
    1. import reusr_txt = "I bought 10 kg apple, 5 kg mango and 12 litre curd for salad."weight_regex = r"\d+ kg"parts = re.split(weight_regex, usr_txt)print("Parts after splitting:", parts)Output: Parts after splitting: ['I bought ', ' apple, ', ' mango and 12 litre curd for salad.'] 📌 Simple idea: re.split() cuts text wherever the pattern appears.

6. re.sub()

    6.1 🔁 What is re.sub()?
    1. re.sub() replaces matches of a pattern with another value. It returns the modified string. Syntax: re.sub(pattern, replacement, text)
Python Regex: sub function
Python Regex: sub function
    6.2 Example: Replace Weight Values
    1. import reusr_txt = "I bought 10 kg apple, 5 kg mango and 12 litre curd for salad."weight_regex = r"\d+ kg" replacement = "X kg"new_txt = re.sub(weight_regex, replacement, usr_txt)print("Modified text:", new_txt)Output: Modified text: I bought X kg apple, X kg mango and 12 litre curd for salad. 📌 re.sub() is used when we want to clean or replace matching text.

7. Quick Comparison of Common re Functions

FunctionPurposeReturns
re.search()Finds the first matchMatch object or None
re.findall()Finds all matchesList
re.split()Splits text by patternList
re.sub()Replaces matched patternString

8. Practical Example: Extract Phone Numbers

    8.1 Phone Number Example
    1. import reusr_txt = "Ram: 9841000000, Sita: 9812345678, Hari: 014445566"phone_regex = r"9[78]\d{8}"phones = re.findall(phone_regex, usr_txt)print("Phone numbers:", phones)Output: Phone numbers: ['9841000000', '9812345678'] 📌 014445566 is not matched because it does not follow the mobile number pattern.

9. Practical Example: Extract Email-like Text

10. Practical Example: Replace Extra Spaces

    10.1 Cleaning Extra Spaces
    1. import reusr_txt = "Python is fun"space_regex = r"\s+"clean_txt = re.sub(space_regex, " ", usr_txt)print(clean_txt)Output: Python is fun 📌 This is useful for text cleaning.
Ad PlaceholderSlot: 7421026683

Practice QuestionsNot started

  1. Python Regex Practice

    Question 1 of 1

    • Extract all email, website and phone numbers from contact_info.txt.
    • Extract timestamp, level, service, thread, message from app.log. Save it as log.csv.
Ad PlaceholderSlot: 5413242224