use strict;
my $str = '<div class="blahblahblah testing"><ul><li>Test 1</li><li>Test 2</li></ul></div><div> </div><p> </p><div class="blahblah"> </div><div class="test2"><p class="blah"> </p><p> </p></div><div class="blahblah"> </div><p> </p><div class="blahblah">Testing</div><div><p> </p></div>
<p> </p>
<p> <p> </p> </p>
<div> <p><p> </p> </p> </div>';
my $regex = qr~
<
(?:
!--[^-]*(?:-(?!->)[^-]*)*-->[^<]*(*SKIP)(*F) # skip comments
|
( # group 1
(p|div) # tag name in group 2
[^"'>]*+ #'"# all that is not a quote or a closing angle bracket
(?: # quoted attributes
"[^\\"]*(?:\\.[^\\"]*)*+" [^"'>]* #'"# double quote
|
'[^\\']*(?:\\.[^\\']*)*+' [^"'>]* #'"# single quote
)*+
>
\s*(?: \s*)* # added (bobble bubble)
(?:
<!--[^-]*(?:-(?!->)[^-]*)*+--> \s* # html comments
|
<(?1) \s* # recursion with the group 1
)*+
\s*(?: \s*)* # added (bobble bubble)
</\2> # closing tag
) # end of the group 1
)
~sxip;
if ( $str =~ /$regex/g ) {
print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
# print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
# print "Capture Group 2 is $2 ... and so on\n";
}
# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Perl, please visit: http://perldoc.perl.org/perlre.html