Exercise 1: Four Levels of Nesting — Possible Solution ==================================================================== THE TEST ------------------------------ naive_extract("
Deepest
", "div") RESULT ------------------------------ ['
Deepest'] THE PATTERN ------------------------------ 2 levels deep: "
Inner
" -> captures '
Inner' (1 stray opening tag) 3 levels deep: "
Deep
" -> captures '
Deep' (2 stray opening tags) 4 levels deep: "
Deepest
" -> captures '
Deepest' (3 stray opening tags) The rule: N levels of nesting leaks exactly N-1 stray opening tags into the "captured" result. WHY THIS WORKS AS AN ANSWER ------------------------------ The regex always starts matching at the FIRST
in the string and scans forward, capturing every raw character until it hits the first literal
-- with zero awareness that any of the div tags along the way were themselves opening tags. Every additional level of nesting adds exactly one more
opening tag between the true outer tag and the first closing tag the regex will find -- and since the regex has no counter tracking how many of those openings it has already passed, every single one of them gets swept into the "content" it reports. The relationship is linear and exact: it isn't that deeper nesting makes the regex "more confused" in some vague sense -- it fails by precisely one additional leaked tag per additional level, which is exactly what you'd expect from a tool that is counting zero levels of anything at all.