Python Regular Expressions Guide | Generated by AI

Home 2025.10

Importing the re Module

The re module (short for regular expressions) is part of Python’s standard library. It’s not a separate “regex package” but a built-in module. Import it at the top of your script:

import re

Basic Concepts

Regular expressions (regex) are patterns used to match, search, and manipulate strings. They use special characters like:

Examples are based on Python’s re documentation. Always compile complex patterns for efficiency with re.compile().

Key Functions and Usage

1. Matching a Pattern at the Start

Example:

   import re
   result = re.match(r"Hello", "Hello world")
   print(result.group())  # Output: Hello

2. Searching Anywhere in the String

Example:

   result = re.search(r"world", "Hello world")
   print(result.group())  # Output: world

3. Finding All Matches

Example:

   matches = re.findall(r"\d+", "I have 3 cats and 42 dogs")
   print(matches)  # Output: ['3', '42']

4. Splitting Strings

Example:

   parts = re.split(r"\s+", "Hello    world   example")
   print(parts)  # Output: ['Hello', 'world', 'example']

5. Replacing Matches

Example:

   new_string = re.sub(r"bad", "good", "This is bad")
   print(new_string)  # Output: This is good

6. Compiling Patterns for Reuse

Example:

   pattern = re.compile(r"\d+")
   matches = pattern.findall("Room 101 and 102")
   print(matches)  # Output: ['101', '102']

Best Practices

If you have a specific use case or error, provide more details!


Back

x-ai/grok-code-fast-1

Donate