Python Regular Expression

Om_Sahoo June 01, 2026

Regular Expressions (Regex) in Python are special sequences of characters used for pattern matching and text processing. It help in searching, validating, extracting, and replacing text efficiently. RegEx can be used to check if a string contains the specified search pattern. Python provides the built-in re module to work with regular expressions.

common Regex Symbols

   Symbol               Meaning
    .                  Any character except newline
   \d                  Any digit (0–9)
   \w                  Any letter, digit, or underscore
   \s                  Any whitespace character
    *                  Zero or more occurrences
    +                  One or more occurrences
    ?                  Zero or one occurrence
    ^                  Start of string          
    $                  End of string

Syntex

import re

re.search(pattern,string)
re.match(pattern,string)
re.findall(pattern,string)
re.sub(pattern,replace,string)

1.The findall()function returns a list containing all matches.

import re 
txt = "i am in CTTC"
x = re.findall("in",txt)
print(x)


Output

in
import re
data = """Customer Records - June 2026

Name: Rahul Sharma
Email: [email protected]
Phone: +91-9876543210
City: Kolkata

Name: Priya Das
Email: [email protected]
Employee ID: EMP1023
Department: HR

For technical support, contact [email protected] or [email protected].

Order Details:
Order ID: ORD-56789
Customer Email: [email protected]
Amount: ₹4,500

Marketing Team:
[email protected]
[email protected]

Random text without email.
Website: www.example.com
Date: 01-06-2026

Emergency Contacts:
[email protected]
[email protected]

End of report."""

emails = re.findall(r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}', data)
print (emails)

Output

['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']

2.The search() function searches the string for a match, and returns a Match object if there is a match.

import re

txt = "The rain in Spain"
x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start())


Output

The first white-space character is located in position: 3

Note:If there is more than one match, only the first occurrence of the match will be returned.

import re

txt = "I am in india"
x = re.search("Odisha", txt)
print(x)
y = re.search("in",txt)
print(x)

Output

None
<re.Match object; span=(5, 7), match='in'>

3.The split() function returns a list where the string has been split at each match:

import re

expr = "x=10+y*5/2"

tokens = re.split(r'([=+\-*/])', expr)

print(tokens)

Output

['x', '=', '10', '+', 'y', '*', '5', '/', '2']
import re 
date = "02-02/2026"
x = re.split(r'[-/]',date)
print(x)

Output

['02', '02', '2026']
0 Likes
61 Views

Filters

No filters available for this view.

Reset All