Hackforge Academy

Category: python

Python Regular Expressions

Published on 24 Jul 2026

Explanation

Regular Expressions (Regex) are powerful patterns used to search, match, and manipulate text. Python provides the built-in re module to

Code:

import re

text = 'My phone number is 9876543210'

pattern = r'\d{10}'

match = re.search(pattern, text)

if match:
    print('Phone Number Found:', match.group())
else:
    print('Phone Number Not Found')

Explanation

The re module provides several useful functions for working with text. re.search() finds the first occurrence of a pattern, re.match()

Code:

import re

text = 'Python Java Python React Java Python'

print(re.findall('Python', text))

print(re.sub('Python', 'AI', text))

print(re.split(' ', text))

if re.match('Python', text):
    print('Text starts with Python')
else:
    print('Text does not start with Python')

Explanation

The datetime module provides classes for working with dates and times in Python. It allows developers to retrieve the current

Code:

from datetime import datetime

current = datetime.now()

print('Current Date and Time:', current)

print('Year:', current.year)
print('Month:', current.month)
print('Day:', current.day)
print('Hour:', current.hour)
print('Minute:', current.minute)
print('Second:', current.second)

Explanation

Python allows developers to format dates into readable strings using the strftime() method and convert strings back into datetime objects

Code:

from datetime import datetime, timedelta

current_date = datetime.now()

print(current_date.strftime('%d/%m/%Y'))
print(current_date.strftime('%d-%m-%Y %H:%M:%S'))

future_date = current_date + timedelta(days=7)
past_date = current_date - timedelta(days=30)

print('After 7 Days:', future_date)
print('30 Days Ago:', past_date)

Explanation

Regular expressions and the datetime module are often used together in real-world applications. For example, a registration system may validate

Code:

import re
from datetime import datetime

email = 'student@example.com'

pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

if re.match(pattern, email):
    print('Valid Email')
    print('Registration Time:', datetime.now().strftime('%d-%m-%Y %H:%M:%S'))
else:
    print('Invalid Email Address')

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community