Regular expressions · 5 / 15 Theory

Anchors, flags and good practices

Anchors

Anchors do not consume characters: they indicate a position in the text.

PatternPosition
^Start of the text
$End of the text
\bWord boundary
import re

print(bool(re.search(r"^Hello", "Hello world")))    # True
print(bool(re.search(r"world$", "Hello world")))    # True

print(re.findall(r"\bsun\b", "sun sunny sun sunset"))   # ['sun', 'sun']

With \b, sun only matches as a whole word, not inside sunny or sunset.

Flags

Flags change how the pattern is interpreted. They are passed with the flags argument:

FlagEffect
re.IGNORECASE (re.I)Ignores upper and lower case
re.MULTILINE (re.M)^ and $ work on each line
re.DOTALL (re.S). also matches the newline
import re

print(re.findall(r"python", "Python and PYTHON", flags=re.IGNORECASE))
# ['Python', 'PYTHON']

text = "one\ntwo\nthree"
print(re.findall(r"^\w+", text, flags=re.MULTILINE))
# ['one', 'two', 'three']

Common mistakes

  • Forgetting the r: without a *raw* string, "\b" is a backspace, not a word boundary. Always write r"\b".
  • Using match or search to validate: re.search(r"\d{5}", "123456") finds five digits and is true. To validate, use fullmatch.
  • Not escaping the dot: . matches any character; for a literal dot write \..
  • Forgetting that findall with groups changes the result (it returns only what was captured).
  • Too greedy patterns: .+ can eat more than you think; try .+?.

When NOT to use regular expressions

Regexes are powerful, but not always the best tool. If in, startswith, split or replace is enough, use them: they are easier to read.

text = "report_2026.pdf"

# Clearer without a regex:
print(text.endswith(".pdf"))   # True

And some things should not be parsed with regex: full HTML, JSON or real dates (31/02 does not exist). That is what json, datetime or specific libraries are for. A regex checks the format, not the meaning.

Tips

  • Start with a simple pattern and make it more complex bit by bit.
  • Test it with examples that should match and others that should not.
  • Use named groups when the pattern grows.
  • Write a comment explaining the pattern: in a month you will not remember it.

Finish the lesson with Validate emails, where you combine classes, quantifiers and fullmatch.