Exercise 2: Different-Tag Nesting — Possible Solution ==================================================================== THE TEST ------------------------------ html = "

Hello bold world

" naive_extract(html, "p") depth_aware_extract_first(html, "p") RESULT ------------------------------ naive_extract: ['Hello bold world'] depth_aware_extract_first: 'Hello bold world' Both approaches agree, and both are correct. WHY THE NAIVE REGEX DOESN'T TRIP UP HERE ------------------------------ naive_extract's own pattern is built specifically around ONE tag name at a time: f"<{tag}>(.*?)" -- for this call, that's literally

(.*?)

. The regex engine is only ever watching for the exact strings "

" and "

". The and tags in the middle are just ordinary characters to it, as far as the pattern matching goes -- no different from if the text had said "Hello *bold* world" with literal asterisks. Since there's only ONE

and ONE

anywhere in the string, the non-greedy capture correctly grabs everything between them, bold tag and all. WHY SAME-TAG NESTING IS GENUINELY DIFFERENT ------------------------------ The chapter's own broken example, "
Inner
", fails because the pattern is specifically hunting for -- and the FIRST the scan encounters isn't the one that closes the outer div at all; it's the one that closes the INNER div, which happens to be spelled with the exact same three characters. The regex has no way to tell "the that closes the div two levels in" apart from "the that closes the outermost div" -- they are literally the same six-character string, and a regex matches strings, not tree positions. Nesting a DIFFERENT tag inside never creates that ambiguity, because a different tag's own closing sequence () can never be confused with the one the pattern is actually searching for (

). The failure this chapter demonstrates is specifically about a tag closing itself prematurely because an identically-named tag opened again first -- not about nesting in general.