Regular expressions are good for many things, but parsing HTML with them is not easy if your problem space goes beyond the trivial.

To solve your problem as you told above with regular expressions, use the following:

use strict; while (<DATA>) { chomp; my $match = "'$1'" if m#^<p>((?:[^<]*|<(?!b>)[^>]+>)*?)</p>$#ism; $match = "<nothing>" unless defined $match; print "$_ matches $match\n" }; __DATA__ <p>this should match</p> <p>This should <b>not</b> match</p> <p>What about <a href="http://www.example.com">this</a>?</p> <p>And <p>this</p> malformed piece?</p>

But in general, you will be better off by looking at the various HTML parsers, for example HTML::TokeParser::Simple, or by looking at the modules to strip HTML, like HTML::TagStripper.

If you are interested in extracting specific text out of webpages, there also is a variety of modules to use. Personally, I like XML::LibXML very much because XPath is a very convenient way to extract text. The following XPath expression finds all p tags that do not contain any b tag as a child, and returns the text:

//p[not descendant::b()]/text()

In reply to Re: Regular expression matching by Corion
in thread Regular expression matching by murugu

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.