Lesson 21: Regular Expressions in Python

๐ŸŽฏ Lesson Objective

To understand and apply Regular Expressions (RegEx) in Python for searching, validating, and manipulating text patterns efficiently.


๐Ÿงฉ 1. What Are Regular Expressions?

Regular Expressions (RegEx) are special patterns used to match strings or parts of strings.
Python provides the re module to work with these expressions.

โœ… Importing RegEx Module:

import re

โš™๏ธ 2. Common RegEx Functions

FunctionDescription
re.search()Finds the first match in a string
re.findall()Returns all matches as a list
re.match()Checks if string starts with the pattern
re.split()Splits string by the matched pattern
re.sub()Replaces pattern with a new string

๐Ÿ” 3. Basic Examples

Example 1 โ€“ search()

import re
text = "My phone number is 9876543210"
pattern = r"\d{10}"
match = re.search(pattern, text)
print(match.group())

Output:

9876543210

Example 2 โ€“ findall()

text = "Emails: user1@gmail.com, user2@yahoo.com"
emails = re.findall(r'\S+@\S+', text)
print(emails)

Output:

['user1@gmail.com', 'user2@yahoo.com']

Example 3 โ€“ match()

text = "Python is powerful"
result = re.match(r"Python", text)
print(result)

Output:

<re.Match object; span=(0, 6), match='Python'>

Example 4 โ€“ split()

text = "apple,banana;orange grape"
words = re.split(r'[;,\s]+', text)
print(words)

Output:

['apple', 'banana', 'orange', 'grape']

Example 5 โ€“ sub()

text = "My number is 9876543210"
new_text = re.sub(r'\d+', '**********', text)
print(new_text)

Output:

My number is **********

๐Ÿงฑ 4. Common RegEx Patterns

PatternMeaningExample Match
\dDigit (0โ€“9)3
\DNon-digitA
\wWord character (aโ€“z, 0โ€“9, _)a
\WNon-word character@
\sWhitespace(space, tab)
^Start of string^Python
$End of stringend$
.Any character (except newline)c.t โ†’ cat, cot
*0 or more repetitionslo*l โ†’ ll, lol, loool
+1 or more repetitionsgo+ โ†’ go, goo, gooo
{n}Exactly n times\d{4} โ†’ 2025
``OR condition
[]Character set[A-Z] matches Aโ€“Z

๐Ÿง  5. Real-Life Use Cases

  • Validate email, phone number, or passwords
  • Extract data from text (e.g., IDs, numbers, dates)
  • Find or replace text in logs or documents
  • Split structured text (CSV, JSON strings)

๐ŸŒ 6. Real-Life Example โ€“ Email Validation

import re

email = "sameer123@gmail.com"
pattern = r'^[a-zA-Z0-9._]+@[a-z]+\.[a-z]+$'

if re.match(pattern, email):
    print("Valid email address!")
else:
    print("Invalid email address!")

Output:

Valid email address!

๐Ÿ’ฌ 7. Password Strength Validation

password = "Pa$$word123"
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'

if re.match(pattern, password):
    print("Strong password!")
else:
    print("Weak password!")

Output:

Strong password!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *