Python Programming

Regular Expressions (Regex) in Python

Introduction

Regular Expressions (Regex) are powerful patterns used to:

  • Search text
  • Validate input
  • Extract information
  • Replace text
  • Split strings

Instead of manually checking every character, Regex allows us to describe patterns.

Example:

Find all email addresses
Find all phone numbers
Find all dates
Find all URLs
Validate passwords

What is a Regular Expression?

A regular expression is a pattern that describes a set of strings.

Example:

\d

Means:

Any digit (0-9)

Example:

123

Matches:

1
2
3

Why Use Regex?

Without Regex:

if (
    '@' in email and
    '.' in email
):
    print("Valid")

With Regex:

import re

pattern = r"\S+@\S+\.\S+"

More powerful and flexible.


The re Module

Python provides the built-in:

re

module.

Import:

import re

Basic Regex Functions

Function Purpose
re.search() Find first match
re.match() Match from beginning
re.fullmatch() Match entire string
re.findall() Find all matches
re.finditer() Iterator of matches
re.sub() Replace matches
re.split() Split using regex
re.compile() Compile pattern

re.search()

Searches entire string.


Example

import re

text = "Python is awesome"

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

print(result)

Output:

<re.Match object>

Check Match

if result:
    print("Found")

Output:

Found

re.match()

Matches only from the beginning.

Example:

import re

text = "Python is awesome"

print(
    re.match("Python", text)
)

Output:

Match Found

Example:

re.match("awesome", text)

Output:

None

Because:

awesome

does not start the string.


re.fullmatch()

Entire string must match.

Example:

import re

print(
    re.fullmatch(
        "Python",
        "Python"
    )
)

Output:

Match

Example:

re.fullmatch(
    "Python",
    "Python Programming"
)

Output:

None

re.findall()

Returns all matches.

Example:

import re

text = "Cat Bat Rat"

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

print(result)

Output:

['at', 'at', 'at']

re.finditer()

Returns match objects.

Example:

import re

text = "Cat Bat Rat"

for match in re.finditer(
    "at",
    text
):
    print(match.start())

Output:

1
5
9

Special Characters

Regex becomes powerful using special symbols.


Dot (.)

Matches any character.

Pattern:

r"c.t"

Matches:

cat
cut
cot
c9t

Example:

import re

print(
    re.findall(
        r"c.t",
        "cat cut cot"
    )
)

Output:

['cat', 'cut', 'cot']

Digit (\d)

Matches:

0-9

Example:

re.findall(
    r"\d",
    "A1 B2 C3"
)

Output:

['1', '2', '3']

Non-Digit (\D)

Matches:

Anything except digits

Example:

re.findall(
    r"\D",
    "A1B2"
)

Output:

['A', 'B']

Word Character (\w)

Matches:

A-Z
a-z
0-9
_

Example:

re.findall(
    r"\w",
    "A_1"
)

Output:

['A', '_', '1']

Non-Word Character (\W)

Matches:

@
#
$
%
!
space

Example:

re.findall(
    r"\W",
    "A@1"
)

Output:

['@']

Whitespace (\s)

Matches:

Space
Tab
Newline

Example:

re.findall(
    r"\s",
    "Hello World"
)

Output:

[' ']

Non-Whitespace (\S)

Matches everything except spaces.


Character Classes []

Example:

r"[abc]"

Matches:

a
b
c

Example

import re

print(
    re.findall(
        r"[abc]",
        "apple ball cat"
    )
)

Output:

['a', 'b', 'a', 'c', 'a']

Range Matching

Pattern:

r"[A-Z]"

Matches:

All uppercase letters

Pattern:

r"[a-z]"

Matches:

All lowercase letters

Pattern:

r"[0-9]"

Matches:

All digits

Quantifiers

Control repetition.


*

Means:

0 or more

Example:

r"ab*"

Matches:

a
ab
abb
abbb

+

Means:

1 or more

Example:

r"ab+"

Matches:

ab
abb
abbb

Not:

a

?

Means:

0 or 1

Example:

r"colou?r"

Matches:

color
colour

Exact Count {}

Example:

r"\d{4}"

Matches:

2025
1234

Example:

re.findall(
    r"\d{4}",
    "Year 2025"
)

Output:

['2025']

Anchors


^

Start of string.

Example:

r"^Python"

Matches:

Python is great

Not:

I love Python

$

End of string.

Example:

r"Python$"

Matches:

I love Python

Combining Anchors

Example:

r"^\d+$"

Meaning:

Only digits

Example

re.fullmatch(
    r"\d+",
    "12345"
)

Match:

Yes

Email Validation Example

import re

email = "[email protected]"

pattern = r"\S+@\S+\.\S+"

if re.fullmatch(
    pattern,
    email
):
    print("Valid")

Output:

Valid

Phone Number Validation

Example:

import re

phone = "9876543210"

if re.fullmatch(
    r"\d{10}",
    phone
):
    print("Valid")

Output:

Valid

Extract All Numbers

import re

text = "Price 100 Qty 25"

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

print(numbers)

Output:

['100', '25']

re.sub()

Replace text.

Example:

import re

text = "Python is great"

result = re.sub(
    "great",
    "awesome",
    text
)

print(result)

Output:

Python is awesome

Remove Digits

import re

text = "A1B2C3"

print(
    re.sub(
        r"\d",
        "",
        text
    )
)

Output:

ABC

re.split()

Split using regex.

Example:

import re

text = "apple,banana;orange"

print(
    re.split(
        r"[,;]",
        text
    )
)

Output:

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

Compiling Patterns

Good for repeated use.

import re

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

print(
    pattern.findall(
        "10 20 30"
    )
)

Common Beginner Mistakes


Mistake 1: Forgetting Raw Strings

Bad:

"\d+"

Good:

r"\d+"

Always prefer:

r"pattern"

Bad:

re.match(
    "cat",
    "I love cat"
)

Output:

None

Use:

re.search()

Mistake 3: Forgetting Quantifiers

Bad:

\d

Matches:

Single digit only

Use:

\d+

for multiple digits.


Mistake 4: Not Using Anchors

Bad:

\d{10}

Can match inside larger text.

Better:

^\d{10}$

Mistake 5: Confusing * and +

Remember:

* = 0 or more

+ = 1 or more

Mistake 6: Using Dot Carelessly

Pattern:

.

Matches nearly everything.

Can produce unexpected results.


Best Practices

✅ Use raw strings

r"\d+"

✅ Use fullmatch() for validation

✅ Compile frequently used patterns

✅ Keep patterns readable

✅ Test regex thoroughly

✅ Use anchors for strict validation


Homework


Q1

Find all digits in:

A1B2C3

Q2

Extract all numbers from:

Price 100 Qty 25

Q3

Validate a 10-digit phone number.


Q4

Validate an email address.


Q5

Replace:

Python

with:

Java

Q6

Split:

apple,banana;orange

using regex.


Q7

Find all uppercase letters.


Q8

Find all words beginning with:

P

Q9

Remove all digits from:

A1B2C3D4

Q10

Check whether a string contains only digits.


Homework Solutions


Solution 1

import re

print(
    re.findall(
        r"\d",
        "A1B2C3"
    )
)

Solution 2

import re

print(
    re.findall(
        r"\d+",
        "Price 100 Qty 25"
    )
)

Solution 3

import re

phone = "9876543210"

print(
    bool(
        re.fullmatch(
            r"\d{10}",
            phone
        )
    )
)

Solution 4

import re

email = "[email protected]"

print(
    bool(
        re.fullmatch(
            r"\S+@\S+\.\S+",
            email
        )
    )
)

Solution 5

import re

print(
    re.sub(
        "Python",
        "Java",
        "Python is good"
    )
)

Solution 6

import re

print(
    re.split(
        r"[,;]",
        "apple,banana;orange"
    )
)

Solution 7

import re

print(
    re.findall(
        r"[A-Z]",
        "AbCDeF"
    )
)

Solution 8

import re

text = "Python PHP Java"

print(
    re.findall(
        r"\bP\w+",
        text
    )
)

Solution 9

import re

print(
    re.sub(
        r"\d",
        "",
        "A1B2C3D4"
    )
)

Solution 10

import re

print(
    bool(
        re.fullmatch(
            r"\d+",
            "12345"
        )
    )
)

Quick Revision

Symbol Meaning
. Any character
\d Digit
\D Non-digit
\w Word character
\W Non-word character
\s Whitespace
\S Non-whitespace
* 0 or more
+ 1 or more
? 0 or 1
{} Exact count
^ Start
$ End
[] Character class

Summary

Regular Expressions (Regex) provide a powerful way to:

  • Search text
  • Extract data
  • Validate input
  • Replace content
  • Split strings

Most commonly used functions:

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

Most commonly used patterns:

\d+
\w+
\s+
[A-Z]
[a-z]
^\d+$

Regex is widely used in:

  • Form validation
  • Email validation
  • Phone validation
  • Log analysis
  • Data extraction
  • Web scraping
  • Text processing

Filters

No filters available for this view.

Reset All