"Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems."

-- Jamie Zaqinski

"You cannot parse [X]HTML with regex."

-- bobince on StackOverflow

I saw this coming with the previous question, and had a response typed, but then thought perhaps I should not come down so strong against the practice. But since my fears have begun to play out, I'll post the gist of what I was going to say before:

Regular Expressions are not an ideal tool for parsing HTML. In the trivial cases, everything will seem to work out fine. But then you'll discover that your problem isn't as trivial as it first appeared, and consequently you will come back here to ask how to further refine (or expand) the capability of the regular expressions you're using. This cycle will repeat until eventually you've got a big nasty unmaintainable, fragile heap of regular expressions that stops working every time you look away. Your time will be wasted trying to fix the HTML parsing code, when it really ought to be spent on something more interesting that hasn't already been solved before, robustly, maintainably, and cleanly.

Look at Mojo::DOM, HTML::Parser::Simple, or HTML::Parser. I prefer the former; it's just so darn easy to use. You will spend an hour or two getting accustomed to using whichever of these tools you settle upon, and will save many hours of headaches as a result.

Abandon the notion that your problem is simple enough to just throw a few regexes at it. Simplicity is elusive, and more so when you introduce regular expressions to a non-regular task.


Dave


In reply to Re: $nextline not working by davido
in thread $nextline not working by qingxia

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.