in reply to Parsing nested HTML with just regex

Well, people, including me, are always saying you shouldn't try to parse HTML with a regexp. It's not because it's impossible. It is possible. But you shouldn't do it because doing it with a regex is non-trivial. The program below will use a regex to extract a div element with a certain id from a piece of limited HTML. I say limited, because the regex doesn't take comments into account, or CDATA declared content. It won't be able to recover from misplaced </div> tags either.
#!/usr/bin/perl use strict; use warnings; $_ = <<'--'; <div id = "foo"> Foo text <div id = "iwant"> Text text. <div id = "insideiwant"> Bla </div> <div id = "alsoinsideiwant"> Bla bla <em>Bla</em>! <div id = "innerinnerdiv"> Inner! </div> </div> </div> </div> -- my $div; $div = qr {<div \s+ (?:id \s* = \s* (?: "[^"]*" | '[^']*' | [-.\d]+))? \s* > (?: (?>[^<]+) | <(?!/?div) | (??{$div}) ) * </div>}ix; my $iwant = qr {<div \s+ id \s* = \s* (?: "iwant" | 'iwant' | iwant) \s* > (?: (?>[^<]+) | <(?!/?div) | (??{$div}) ) * </div>}ix; print $&, "\n" if /$iwant/; # Don't try to be the smartass # to point out potential issues # about $&. They are irrelevant # here. __END__ <div id = "iwant"> Text text. <div id = "insideiwant"> Bla </div> <div id = "alsoinsideiwant"> Bla bla <em>Bla</em>! <div id = "innerinnerdiv"> Inner! </div> </div> </div>

Abigail