Python re Module

Practical regular expressions with compiled patterns and groups.

  • python re
  • re.compile
  • findall
  • named groups
  • regex sub

Python re Module

Practical regular expressions with compiled patterns and groups.

Commands

CommandWhat it does
re.compile(r"\d{4}-\d{2}-\d{2}")Compile once, reuse
pattern.search(text)First match anywhere
pattern.findall(text)All matches
pattern.sub("X", text)Replace matches
re.split(r"\s*,\s*", s)Split on comma + spaces

Example

import re
pat = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})")
m = pat.search("release 2026-10")
print(m.groupdict())  # {'year': '2026', 'month': '10'}

FAQ

search vs match?

search scans the whole string; match anchors at the start — most bugs come from using match unintentionally.

Why raw strings?

Backslashes stay literal (r"\d" not "\\d"); always write patterns as r"...".

الأسئلة الشائعة

search vs match?
search scans the whole string; match anchors at the start — most bugs come from using match unintentionally.
Why raw strings?
Backslashes stay literal (r"\d" not "\\d"); always write patterns as r"...".

Python