LESSON · 1 OF 6

The re module

The re module

Python's regular-expression support lives in the re module, part of the standard library. Import it and you can search text for patterns, pull out matching pieces, and check that a string has the shape you expect.

python
import re

Why raw strings

Regex patterns lean heavily on the backslash: \d for a digit, \. for a literal dot, \s for whitespace. In a normal Python string the backslash is also an escape character, so "\d" is easy to misread and "\n" turns into a newline. To keep a pattern exactly as written, use a raw string by prefixing it with r:

python
pattern = r"\d+\.\d+"

The r tells Python to leave every backslash alone and hand the raw text straight to re. Always write regex patterns as raw strings. It costs nothing and avoids a whole class of confusing bugs.

A first match

The quickest way to try a pattern is re.search, which looks for the pattern anywhere in a string and returns a match object, or None when there's nothing:

python
import re

text = "release 1.20 shipped"
match = re.search(r"\d+\.\d+", text)
if match:
    print(match.group())   # 1.20

match.group() returns the slice of text the pattern matched. A None result means no match, which is why the if guard matters before you call .group().

What this node introduces

  • import re loads the regular-expression module.
  • Raw strings (r"...") keep backslashes intact in patterns.
  • re.search(pattern, text) returns a match object or None.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute