in reply to Regular expression matching
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()
|
|---|