Bird
Raised Fist0
PythonHow-ToBeginner · 3 min read

How to Use Regex in Python: Simple Guide with Examples

In Python, you use regex by importing the re module and applying functions like re.search(), re.match(), or re.findall() with a pattern string. Regex patterns let you find, match, or replace text based on rules you define.
📐

Syntax

To use regex in Python, first import the re module. Then use functions like re.search(pattern, string) to find a pattern anywhere in the string, re.match(pattern, string) to check if the string starts with the pattern, or re.findall(pattern, string) to get all matches.

The pattern is a string that defines the regex rules, and string is the text you want to search.

python
import re

pattern = r"\d+"  # matches one or more digits
text = "There are 12 apples and 30 bananas."

match = re.search(pattern, text)
if match:
    print("Found:", match.group())
Output
Found: 12
💻

Example

This example shows how to find all numbers in a text using re.findall(). It prints each number found.

python
import re

text = "My phone numbers are 123-456-7890 and 987-654-3210."
pattern = r"\d{3}-\d{3}-\d{4}"
numbers = re.findall(pattern, text)

for number in numbers:
    print(number)
Output
123-456-7890 987-654-3210
⚠️

Common Pitfalls

  • Forgetting to use raw strings (prefix r) for regex patterns can cause errors because backslashes are treated as escape characters.
  • Using re.match() when you want to find a pattern anywhere in the string instead of only at the start.
  • Not checking if a match was found before calling .group(), which causes errors.
python
import re

text = "Hello 123"
pattern = "\\d+"  # Without raw string, backslash must be doubled

# Wrong: no raw string, might cause confusion
match = re.search(pattern, text)
if match:
    print("Found:", match.group())

# Correct: use raw string for pattern
pattern = r"\d+"
match = re.search(pattern, text)
if match:
    print("Found:", match.group())
Output
Found: 123 Found: 123
📊

Quick Reference

Here are some common regex functions and their uses in Python:

FunctionPurpose
re.search(pattern, string)Finds first match anywhere in string
re.match(pattern, string)Checks if string starts with pattern
re.findall(pattern, string)Returns all matches as a list
re.sub(pattern, repl, string)Replaces matches with repl
re.compile(pattern)Prepares regex pattern for reuse
✅

Key Takeaways

Always import the re module to use regex in Python.
Use raw strings (r"pattern") to write regex patterns safely.
Use re.search() to find a pattern anywhere, re.match() only at start.
Check if a match exists before accessing match.group() to avoid errors.
re.findall() returns all matches as a list for easy processing.