← Reference notes

Python regular expressions (re) basics

Python regular expressions (re) basics

Summary

Python's re module matches text against patterns. Write patterns as raw strings (r"..."). re.search finds a match anywhere, re.match only at the start, and re.fullmatch needs the whole string to match. findall, finditer and sub handle every match, and groups such as (?P<name>...) capture parts.

Draft. License: CC BY 4.0 (this summary). Sources: [S1] Python Software Foundation, "re: Regular expression operations (Python 3 docs)" (PSF License 2.0 docs; restated in our own words, no copied text); [S2] Python Software Foundation, "Regular Expression HOWTO (Python 3 docs)" (PSF License 2.0 docs; restated in our own words, no copied text).

Example

import re
m = re.search(r"(?P<y>\d{4})-(?P<m>\d{2})", "due 2026-11-02")
if m:
    print(m.group("y"), m.group("m"))   # 2026 11
re.sub(r"\s+", " ", "a   b\n c")          # 'a b c'

Facts

Caveats

Pointers

Source: https://docs.python.org/3/library/re.html · License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted), condensed and paraphrased; sources: Python Software Foundation, Python 3 documentation, re: Regular expression operations (PSF License 2.0); restated in our own words; Python Software Foundation, Python 3 documentation, Regular Expression HOWTO (PSF License 2.0); restated in our own words

Cite this

Permanent ID: iil:note:nh5m2kyp

iinventedlight Library. 2026. "Python regular expressions (re) basics." iinventedlight Library, iil:note:nh5m2kyp, version of 2026-11-02. https://iinventedlight.com/library/reference/python-docs/python-regex-basics/. License: CC-BY-4.0. Summary of https://docs.python.org/3/library/re.html.

@misc{iil_note_nh5m2kyp,
  author = {{iinventedlight Library}},
  title = {{Python regular expressions (re) basics}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-02},
  url = {https://iinventedlight.com/library/reference/python-docs/python-regex-basics/},
  note = {Permanent ID iil:note:nh5m2kyp. License: CC-BY-4.0. Summary of https://docs.python.org/3/library/re.html.},
}

For language models and agents: start at /llms.txt. This page in Markdown: /library/reference/python-docs/python-regex-basics.md.