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}>(.*?){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 ONEand 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, "