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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.