Python Mastery – From Basics to Brilliance / Python Libraries for Real-World Use

Regex – Pattern Matching

πŸ” Regular Expressions (Regex)

Regex (Regular Expression) is a pattern used to search, match, and manipulate text.

Python provides the re module for working with Regex.

import re

πŸ”Ή Basic Example

Find whether a word exists in a string:

import re

text = "I love Python"

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

print(result)

If "Python" is found, re.search() returns a match object.


🧩 Common Regex Patterns

Pattern

Meaning

Example

.

Any character

a.c β†’ abc

^

Starts with

^Hello

$

Ends with

world$

*

0 or more

ab*

+

1 or more

ab+

?

0 or 1

ab?

\d

Digit

123

\D

Non-digit

abc

\w

Word character

Python_1

\W

Non-word character

@

\s

Whitespace

space

\S

Non-whitespace

A

[abc]

Any of a, b, c

a

[0-9]

Any digit

5


πŸ› οΈ Common re Functions

re.search()    # Find first match
re.match()     # Match at the beginning
re.findall()   # Find all matches
re.sub()       # Replace matches
re.split()      # Split using a pattern

Example β€” findall()

import re

text = "I have 10 apples and 20 oranges."

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

print(numbers) #['10', '20']