I love that tree comment. It is a classic. :-)

The tree structure involves such details as the fact that tags must balance and can involve nested tables. Matching nesting with a single regular expression is impossible, you cannot even construct an RE that tests whether parentheses balance!

Another major detail you are skipping over is the fact that there are a lot of constructs which are invalid HTML but the browsers attempt to work around. In a real environment if someone can find some broken construct that escapes your match but gets interpreted the right way by some browser, that is a major oops.

Enjoy your RE, but I won't trust it. At some point you need to stop thinking about this as a matching problem which RE's are designed for) and start thinking of this as a parsing problem (which REs are a useful tool for but are only a piece of the puzzle). As soon as you start saying that you are parsing the document, it becomes trivial to be sure that you are not missing anything and you will guarantee that you put out a valid document which cannot cause confusion.

Random thought: Have you thought about how you will catch someone who just puts <-- somewhere? What if someone designs a tag which you strip out - and in the process turn something you skipped because it was an invalid tag into a valid one? How many more of these can you think of, and how are you going to convince me that you have caught them all?

A non-RE solution can easily - demonstrably - result in output that is absolutely guaranteed to be safe. I stand by my doubt that an RE solution will ever achieve that status.


In reply to Re (tilly) 4: HTML Matching by tilly
in thread HTML Matching by spaz

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.