m#<([^"'>]+|"[^"]*"|'[^']*')*>#

will match (if I'm not missing something) properly formed HTML/XML tags (as well as other similar things, which is okay because such other similar things shouldn't be found in proper HTML/XML).

To return the matched tag in $1, use (or put the parens inside the <> as I do below since that part of the tag is constant): m#(<(?:[^"'>]+|"[^"]*"|'[^']*')*>)# Note that this doesn't handle HTML comments. To properly handle both HTML comments and HTML tags using regexes, you have to march along the text like a real parser:

while( $html !~ m#\G$#gc ) { if( $html =~ m#\G([^&<]+)#gc ) { # $1 is plain text } elsif( $html =~ m#\G<!--(.*?)-->#gc ) { # $1 is a comment # I think HTML comments are defined by the standard # to actually be more complex than that, but the # practical definition appears to match the above. } elsif( $html =~ m#\G<((?:[^"'>]+|"[^"]*"|'[^']*')*)>#gc ) { # $1 is the inside of a tag } elsif( $html =~ m#\G&(\w+);#gc ) { # $1 is the name of an entity } elsif( $html =~ m!\G&#(\w+);!gc ) { # $1 is the number of an entity } else { # We have hit invalid HTML. # You can try to be lenient here if you like: if( $html =~ m#\G([&<])#gc ) { # Treat like a &amp; or &lt; if you like } else { die "Impossible??"; } } }
I almost find it hard to believe that someone writing a module to parse HTML using just Perl didn't get that much correct... or maybe I can. (:

Updated, but not much.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: parsing HTML by tye
in thread parsing HTML by eod

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.