Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Python RegEx: A Practical Guide to Regular Expressions

2 min read .
Python RegEx: A Practical Guide to Regular Expressions

Regular expressions describe text patterns for searching, validating, extracting, splitting, and replacing strings. Python provides regular-expression support through the standard-library re module.

Start with Raw Strings

Regex patterns often contain backslashes. Raw string literals keep them readable:

import re

pattern = r"\d+"

Without the r prefix, Python string escaping and regex escaping can interact in confusing ways.

Search for a Pattern

re.search() scans the string and returns the first match anywhere in the input:

pattern = r"hello"
text = "say hello to Python"
match = re.search(pattern, text)

if match:
    print(match.group())

match(), search(), and fullmatch()

These functions answer different questions:

re.match(r"abc", "abcdef")
re.search(r"abc", "123abcdef")
re.fullmatch(r"\d{4}", "2026")
  • match() checks from the beginning of the string.
  • search() looks anywhere in the string.
  • fullmatch() requires the entire string to satisfy the pattern.

For validation, fullmatch() often expresses the intent better than manually adding ^ and $.

Common Pattern Syntax

.       any character except newline by default
\d      decimal digit
\w      word character
\s      whitespace
[abc]   one character from the set
[^abc]  one character not in the set
*       zero or more
+       one or more
?       zero or one
{m,n}   between m and n repetitions

For example, a simple date-shaped pattern:

pattern = r"\d{4}-\d{2}-\d{2}"

This validates the shape of a date, not whether values such as month 99 are meaningful. Use datetime when semantic date validation matters.

Capturing Groups

text = "2026-09-01"
match = re.fullmatch(r"(\d{4})-(\d{2})-(\d{2})", text)

if match:
    year, month, day = match.groups()
    print(year, month, day)

Named groups are easier to maintain in larger patterns:

pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
match = re.fullmatch(pattern, "2026-09-01")

if match:
    print(match.group("year"))

Find All Matches

findall() returns matching text values:

numbers = re.findall(r"\d+", "Order 12 contains 3 items")
print(numbers)

For richer match information such as positions and named groups, use finditer():

for match in re.finditer(r"\d+", "Order 12 contains 3 items"):
    print(match.group(), match.span())

Replace Text

text = "one   two\tthree"
normalized = re.sub(r"\s+", " ", text)
print(normalized)

A replacement function can compute values dynamically:

def uppercase(match):
    return match.group().upper()

result = re.sub(r"\b[a-z]+\b", uppercase, "hello python")

Split with a Pattern

parts = re.split(r"[,;]\s*", "red, green; blue")
print(parts)

Flags

Case-insensitive matching:

re.search(r"python", "Python", flags=re.IGNORECASE)

Multiline anchors:

re.findall(r"^ERROR:.*$", log_text, flags=re.MULTILINE)

Verbose mode helps document complex expressions:

pattern = re.compile(
    r"""
    (?P<year>\d{4})
    -
    (?P<month>\d{2})
    -
    (?P<day>\d{2})
    """,
    re.VERBOSE,
)

Compile Reused Patterns

email_like = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")

Compilation can improve readability when a pattern is reused. Python also caches recently used patterns internally, so explicit compilation is primarily an organizational choice for many applications.

Avoid Overusing Regex

Regular expressions are powerful, but ordinary string methods are clearer for simple operations:

filename.endswith(".csv")
"error" in message
text.removeprefix("user:")

Also avoid treating a small regex as a complete validator for complicated standards such as email addresses, URLs, or programming-language syntax when a dedicated parser is available.

Conclusion

Use Python’s re module when the problem is genuinely pattern-based. Prefer raw strings, choose search() versus fullmatch() deliberately, use named groups for complex extraction, and fall back to simpler string methods whenever they express the task more clearly.

Related Posts

chevron-up