Skip to content

Instantly share code, notes, and snippets.

@dbohdan
Created October 11, 2025 18:39
Show Gist options
  • Select an option

  • Save dbohdan/7de18b7a564978d073283dfae5b0213f to your computer and use it in GitHub Desktop.

Select an option

Save dbohdan/7de18b7a564978d073283dfae5b0213f to your computer and use it in GitHub Desktop.

A tiny introduction to regular expressions in Python

  1. Import the module: import re

  2. Basic match: re.search(r'cat', 'concatenate') → finds 'cat' anywhere.

  3. Full match: re.fullmatch(r'cat', 'cat') → must match the entire string.

  4. Find all: re.findall(r'\d+', 'a1b22c333')['1', '22', '333']

  5. Replace: re.sub(r'\s+', ' ', 'too many spaces')'too many spaces'

  6. Character classes:

    • \d digits, \w word chars, \s whitespace
    • . any char except newline
  7. Quantifiers:

    • + one or more, * zero or more, ? optional, {n,m} range
  8. Anchors: ^ start, $ end, \b word boundary

  9. Groups:

    • re.search(r'(ha)+', 'hahaha').group(1)'ha'
    • Named: (?P<name>pattern)
  10. Raw strings: Always use r'pattern' to avoid problems with escaping.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment