Lesson 59 of 70 – Python Regular Expressions
84%

Python Regular Expressions

Regular Expressions, commonly called Regex, are patterns used to search, match, and manipulate text.

Python provides the built-in re module for working with regular expressions.

Note: Regular expressions are useful for tasks such as finding words, validating email addresses, extracting numbers, replacing text, and searching complex text patterns.
What is Regular Expression?

A regular expression is a sequence of characters that defines a search pattern.

For example, the pattern cat can be used to search for the word "cat".

import re

text = "The cat is sleeping."

result = re.search("cat", text)

print(result)
Output:
<re.Match object ...>
Importing the re Module

Python's regular expression functionality is provided by the built-in re module.

import re

After importing the module, you can use functions such as:

  • re.search()
  • re.match()
  • re.findall()
  • re.finditer()
  • re.sub()
  • re.split()
  • re.fullmatch()
re.search()

The re.search() function searches the entire string for the first location where the pattern matches.

import re

text = "I am learning Python."

result = re.search("Python", text)

if result:
    print("Pattern found")
Output:
Pattern found
re.match()

The re.match() function checks for a match at the beginning of the string.

import re

text = "Python is easy."

result = re.match("Python", text)

if result:
    print("Match found")
Output:
Match found

If the pattern does not occur at the beginning, re.match() returns None.

re.fullmatch()

The re.fullmatch() function succeeds only when the entire string matches the pattern.

import re

text = "Python"

result = re.fullmatch("Python", text)

if result:
    print("Full match")
Output:
Full match
re.findall()

The re.findall() function returns all non-overlapping matches as a list.

import re

text = "Python is easy. Python is powerful."

result = re.findall("Python", text)

print(result)
Output:
['Python', 'Python']
re.finditer()

The re.finditer() function returns an iterator containing match objects.

import re

text = "Python is easy. Python is powerful."

matches = re.finditer("Python", text)

for match in matches:
    print(match.group())
Output:
Python
Python
re.sub()

The re.sub() function replaces matches with another string.

import re

text = "I like Java."

new_text = re.sub("Java", "Python", text)

print(new_text)
Output:
I like Python.
re.split()

The re.split() function splits a string wherever the pattern matches.

import re

text = "apple,banana,orange"

result = re.split(",", text)

print(result)
Output:
['apple', 'banana', 'orange']
Character Classes

Character classes allow you to match specific types or groups of characters.

Pattern Meaning
[abc] Matches a, b, or c
[^abc] Matches a character other than a, b, or c
[a-z] Matches lowercase letters from a to z
[A-Z] Matches uppercase letters from A to Z
[0-9] Matches a digit from 0 to 9
\d – Digit

The \d pattern matches a Unicode decimal digit by default.

import re

text = "My age is 25."

result = re.findall(r"\d", text)

print(result)
Output:
['2', '5']
\d+ – One or More Digits

The + quantifier means one or more occurrences.

import re

text = "My age is 25 and my pin is 1234."

result = re.findall(r"\d+", text)

print(result)
Output:
['25', '1234']
\w – Word Character

The \w pattern matches Unicode word characters by default, including letters, digits, and underscore.

import re

text = "Python_123"

result = re.findall(r"\w", text)

print(result)
Output:
['P', 'y', 't', 'h', 'o', 'n', '_', '1', '2', '3']
\s – Whitespace

The \s pattern matches whitespace characters such as spaces and line breaks.

import re

text = "Hello World"

result = re.findall(r"\s", text)

print(result)
Output:
[' ']
Dot . Pattern

The dot . matches almost any character except a newline by default.

import re

text = "cat"

result = re.findall(r".", text)

print(result)
Output:
['c', 'a', 't']
^ and $ Anchors

The ^ symbol matches the beginning of a string, while $ matches the end.

import re

text = "Python"

result = re.search(r"^Python$", text)

if result:
    print("Exact match")
Output:
Exact match
Quantifiers

Quantifiers specify how many times a pattern can occur.

Quantifier Meaning
* Zero or more
+ One or more
? Zero or one
{n} Exactly n times
{n,} At least n times
{n,m} Between n and m times
Using + Quantifier
import re

text = "I have 123 apples."

result = re.findall(r"\d+", text)

print(result)
Output:
['123']

The + combines consecutive matching digits into one match.

Using * Quantifier
import re

text = "color colour"

result = re.findall(r"colou*r", text)

print(result)
Output:
['color', 'colour']

The * allows the character before it to occur zero or more times.

Using ? Quantifier
import re

text = "color colour"

result = re.findall(r"colou?r", text)

print(result)
Output:
['color', 'colour']

The ? means that the preceding character or group is optional and may occur zero or one time.

Groups

Parentheses () are used to create groups in regular expressions.

import re

text = "My phone is 9876543210"

result = re.search(r"(\d{10})", text)

if result:
    print(result.group(1))
Output:
9876543210
Capturing Multiple Groups
import re

text = "Name: Rahul, Age: 25"

pattern = r"Name: (\w+), Age: (\d+)"

result = re.search(pattern, text)

if result:
    print(result.group(1))
    print(result.group(2))
Output:
Rahul
25
Alternation | Operator

The | symbol means "or".

import re

text = "I like Python"

result = re.search(r"Python|Java", text)

if result:
    print(result.group())
Output:
Python
Raw Strings

Raw strings are commonly used when writing regular expressions because backslashes do not need to be escaped in the same way as ordinary Python strings.

pattern = r"\d+"

print(pattern)
Output:
\d+

Using r"..." makes regex patterns easier to read, especially when they contain many backslashes.

Finding an Email Address
import re

text = "Contact us at hello@example.com"

pattern = r"[\w.-]+@[\w.-]+\.\w+"

result = re.search(pattern, text)

if result:
    print(result.group())
Output:
hello@example.com
Note: Regex can be useful for basic email-pattern checks, but complete email validation can be more complicated than a simple regular expression.
Finding Phone Numbers
import re

text = "Call me at 9876543210"

pattern = r"\b\d{10}\b"

result = re.search(pattern, text)

if result:
    print(result.group())
Output:
9876543210
Case-Insensitive Matching

The re.IGNORECASE flag can be used when uppercase and lowercase differences should be ignored.

import re

text = "Python is powerful."

result = re.search("python", text, re.IGNORECASE)

if result:
    print("Found")
Output:
Found
Compiled Regular Expressions

The re.compile() function creates a compiled regular expression pattern that can be reused.

import re

pattern = re.compile(r"\d+")

text = "Age 25, PIN 1234"

result = pattern.findall(text)

print(result)
Output:
['25', '1234']
Common Regex Symbols
Pattern Meaning
\d Digit
\w Word character
\s Whitespace
. Any character except newline by default
^ Beginning of string
$ End of string
* Zero or more
+ One or more
? Zero or one
| OR
() Group
[] Character class
Key Points
  • Regular expressions are patterns used to search and manipulate text.
  • Python provides the built-in re module.
  • re.search() searches for a pattern anywhere in the string.
  • re.match() checks for a match at the beginning.
  • re.fullmatch() requires the entire string to match.
  • re.findall() returns all non-overlapping matches.
  • re.sub() replaces matching text.
  • re.split() splits text using a regular expression.
  • Quantifiers such as *, +, and ? control repetition.
  • Character classes such as \d, \w, and \s simplify pattern matching.
  • Raw strings are commonly used for readable regex patterns.
  • Regular expressions are useful for searching, extraction, validation, and text replacement.

🧠 Quick Quiz

Question: Which Python module is used for regular expressions?