use strict;
my $str = 'Remove comments from some generated HTML which can be invalid with nested comments
==================================================================================
I would like to remove HTML comments from some generated content.
If I use the regex `/<!--(.*?)-->/` (ungreedy with the `?`) then it works for most cases such as this example:
```html
<!-- <h1> test </h1> --> not remove <!-- <h1> test 2 </h1> -->
```
It gets rid of the `<h1>` tags and leaves the "*not remove*" as desired.
But **if the comments are nested**, then it will not handle it properly as it will leave the last comment closing tag `\'-->\'`. The workaround would be to use a greedy pattern, but in this case it will not work for the first case, with multiple comments.
Example of nested comments (I know it\'s not valid HTML, but it\'s the backend which is generating it):
```html
text <!-- something <!-- <p> test </p> --> need remove -->
```
I\'ve tried to find a solution, but I don\'t know how to solve this. Has anyone an idea how to handle it?
<!-- multiline
comment -->
<!-- <footer>Footer with
nested <!-- comment -->
on several lines.</footer>
-->';
my $regex = qr/<!--(?:(?!<!--|-->).|(?R))*-->/sp;
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