1.3.11Python Intermediate

Regular expressions — re module, patterns, groups, findall, sub

1,765 words8 min readdifficulty · medium6 backlinks

WHY do regexes exist?

The mental model:

  • You give a pattern (a description of a shape).
  • The engine moves a cursor left→right and asks "does the text starting here match my shape?"
  • It reports matches, optionally pulling out groups (sub-pieces you captured).

WHAT are the building blocks?


HOW the 5 key functions differ


The raw-string WHY


Figure — Regular expressions — re module, patterns, groups, findall, sub

Worked examples



Compiling for reuse


Recall Feynman: explain to a 12-year-old

Imagine you have a giant book and you want to highlight every phone number. Instead of reading every line yourself, you give a robot a rule card: "find a chunk that looks like some digits, a dash, some more digits." The robot zooms through and highlights every chunk that fits the card. Regex is that rule card. ( ) is you drawing little boxes on the card saying "and remember what's inside this box separately." findall = "show me every highlight." sub = "replace every highlight with this new text."


Flashcards

What does re.search return when nothing matches?
None (so you must check before calling .group).
Difference between re.match and re.search?
match only checks the start of the string; search scans anywhere.
What does \d+ mean?
One or more digits in a row.
Why use raw strings r"..." for patterns?
So Python doesn't eat the backslash; the regex engine gets \d, \b etc. intact.
What does findall return when the pattern has 2 capturing groups?
A list of tuples, one tuple of group strings per match.
What is group(0)?
The entire matched substring.
How do you make a quantifier lazy?
Add ? after it (e.g. .*?), so it matches as few chars as possible.
In re.sub, what does \1 mean in the replacement string?
The text captured by group 1 (a backreference).
What is a non-capturing group and why use it?
(?:...) groups for structure/alternation without storing it as a numbered group.
What do ^ and $ anchor?
^ = start of string, $ = end of string.
Why is re.match("dog","the dog") None?
match is anchored at position 0; "dog" isn't at the start.
What does re.compile buy you?
Parses the pattern once into a reusable object — faster in loops.

Connections

  • String methods — split, join, format
  • Python Intermediate — File I/O and parsing logs
  • Finite State Machines (regex engines are NFAs/DFAs under the hood)
  • Greedy vs Backtracking algorithms
  • Escape characters and raw strings

Concept Map

describes shape of

built into

repeat previous atom

capture sub-pieces

used by

used by

used by

used by

first match anywhere

only at start pos 0

list of all matches

replaces matches

passes backslash through

findall returns tuples via

Regex pattern language

Regex engine scans text

Pattern atoms

Quantifiers

Capturing groups

re.search

re.match

re.findall

re.sub

Raw strings r-prefix

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Regex matlab ek chhoti si "pattern language" jisse hum text ka shape describe karte hain, exact text nahi. Jaise tum robot ko ek rule-card do: "kuch digits, phir slash, phir aur digits" — aur robot poore log file me se saare dates highlight kar deta hai. Isse tumhe for loops aur split ki gandi chain likhne ki zarurat nahi padti. Yaad rakhne wale 5 verbs: search (kahin bhi pehla match), match (sirf start me), findall (saare matches ki list), sub (sabko replace karo), aur groups (jo ( ) ke andar capture hua).

Sabse important atoms: \d = digit, \w = word char, . = koi bhi ek char, aur quantifiers * (0 ya zyada), + (1 ya zyada), ? (0 ya 1). Ek bada confusion: * ka matlab "anything" nahi hota — wo pichhle atom ko repeat karta hai. "Any text" ke liye .* chahiye. Aur greedy vs lazy bhi yaad rakho: .* zyada se zyada match karega, .*? kam se kam — HTML tags parse karte time ye bachata hai.

Groups (( )) ka kaam hai matched text ke tukde alag se nikalna. Jaise date 05/12/2024 me teen groups: day, month, year. group(0) hamesha poora match deta hai, group(1) pehla box. Aur sub me \1, \2 se tum captured tukde reuse karke text ko reformat kar sakte ho. Ek aakhri tip: pattern hamesha raw string r"\d+" me likho, taaki Python backslash ko kha na jaye.

Go deeper — visual, from zero

Test yourself — Python Intermediate

Connections