<p>I need to match and remove all tags using a regular expression in Perl.  I have the following:</p>

<pre><code>&lt;\\??(?!p).+?&gt;
</code></pre>

<p>But this still matches with the closing <code>&lt;/p&gt;</code> tag.  Any hint on how to match with the closing tag as well?</p>

<p>Note, this is being performed on xhtml.</p>

[{'answer_id': 29871, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 1, 'selected': False, 'text': "<p>Assuming that this will work in PERL as it does in languages that claim to use PERL-compatible syntax:</p>\n\n<p><code>/&lt;\\/?[^p][^&gt;]*&gt;/</code></p>\n\n<p>EDIT:</p>\n\n<p>But that won't match a <code>&lt;pre&gt;</code> or <code>&lt;param&gt;</code> tag, unfortunately.</p>\n\n<p>This, perhaps?</p>\n\n<pre><code>/&lt;\\/?(?!p&gt;|p )[^&gt;]+&gt;/\n</code></pre>\n\n<p>That should cover <code>&lt;p&gt;</code> tags that have attributes, too.</p>\n"}, {'answer_id': 29875, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': "<p>Try this, it should work:</p>\n\n<pre><code>/&lt;\\/?([^p](\\s.+?)?|..+?)&gt;/\n</code></pre>\n\n<p>Explanation: it matches either a single letter except “p”, followed by an optional whitespace and more characters, or multiple letters (at least two).</p>\n\n<p>/EDIT: I've added the ability to handle attributes in <code>p</code> tags.</p>\n"}, {'answer_id': 29887, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 2, 'selected': False, 'text': "<p>Since HTML is not a regular language I would not expect a regular expression to do a very good job at matching it. They might be up to this task (though I'm not convinced), but I would consider looking elsewhere; I'm sure perl must have some off-the-shelf libraries for manipulating HTML.</p>\n\n<p>Anyway, I would think that what you want to match is &lt;/?(p.+|.*)(\\s*.*)&gt; non-greedily (I don't know the vagaries of perl's regexp syntax so I cannot help further).  I am assuming that \\s means whitespace.  Perhaps it doesn't. Either way, you want something that'll match attributes offset from the tag name by whitespace.  But it's more difficult than that as people often put unescaped angle brackets inside scripts and comments and perhaps even quoted attribute values, which you don't want to match against.</p>\n\n<p>So as I say, I don't really think regexps are the right tool for the job.</p>\n"}, {'answer_id': 29892, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>Since HTML is not a regular language</p>\n</blockquote>\n\n<p>HTML isn't but HTML tags are and they can be adequatly described by regular expressions.</p>\n"}, {'answer_id': 29911, 'author': 'Vegard Larsen', 'author_id': 1606, 'author_profile': 'https://Stackoverflow.com/users/1606', 'pm_score': -1, 'selected': False, 'text': '<p>You should probably also remove any attributes on the &lt;p> tag, since someone bad could do something like:</p>\n\n<pre><code>&lt;p onclick="document.location.href=\'http://www.evil.com\'"&gt;Clickable text&lt;/p&gt;\n</code></pre>\n\n<p>The easiest way to do this, is to use the regex people suggest here to search for &amp;ltp> tags with attributes, and replace them with &lt;p> tags without attributes. Just to be on the safe side.</p>\n'}, {'answer_id': 29917, 'author': 'Xetius', 'author_id': 274, 'author_profile': 'https://Stackoverflow.com/users/274', 'pm_score': 5, 'selected': True, 'text': "<p>I came up with this:</p>\n\n<pre><code>&lt;(?!\\/?p(?=&gt;|\\s.*&gt;))\\/?.*?&gt;\n\nx/\n&lt;           # Match open angle bracket\n(?!         # Negative lookahead (Not matching and not consuming)\n    \\/?     # 0 or 1 /\n    p           # p\n    (?=     # Positive lookahead (Matching and not consuming)\n    &gt;       # &gt; - No attributes\n        |       # or\n    \\s      # whitespace\n    .*      # anything up to \n    &gt;       # close angle brackets - with attributes\n    )           # close positive lookahead\n)           # close negative lookahead\n            # if we have got this far then we don't match\n            # a p tag or closing p tag\n            # with or without attributes\n\\/?         # optional close tag symbol (/)\n.*?         # and anything up to\n&gt;           # first closing tag\n/\n</code></pre>\n\n<p>This will now deal with p tags with or without attributes and the closing p tags, but will match pre and similar tags, with or without attributes.</p>\n\n<p>It doesn't strip out attributes, but my source data does not put them in.  I may change this later to do this, but this will suffice for now.</p>\n"}, {'answer_id': 29965, 'author': 'dbr', 'author_id': 745, 'author_profile': 'https://Stackoverflow.com/users/745', 'pm_score': 2, 'selected': False, 'text': "<p>Not sure why you are wanting to do this - regex for HTML sanitisation isn't always the best method (you need to remember to sanitise attributes and such, remove javascript: hrefs and the likes)... but, a regex to match HTML tags that aren't <code>&lt;p&gt;&lt;/p&gt;</code>:</p>\n\n<p><code>(&lt;[^pP].*?&gt;|&lt;/[^pP]&gt;)</code></p>\n\n<p>Verbose:</p>\n\n<pre><code>(\n    &lt;               # &lt; opening tag\n        [^pP].*?    # p non-p character, then non-greedy anything\n    &gt;               # &gt; closing tag\n|                   #   ....or....\n    &lt;/              # &lt;/\n        [^pP]       # a non-p tag\n    &gt;               # &gt;\n)\n</code></pre>\n"}, {'answer_id': 29985, 'author': 'John Siracusa', 'author_id': 164, 'author_profile': 'https://Stackoverflow.com/users/164', 'pm_score': 5, 'selected': False, 'text': '<p>If you <em>insist</em> on using a regex, something like this will work in most cases:</p>\n\n<pre><code># Remove all HTML except "p" tags\n$html =~ s{&lt;(?&gt;/?)(?:[^pP]|[pP][^\\s&gt;/])[^&gt;]*&gt;}{}g;\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>s{\n  &lt;             # opening angled bracket\n  (?&gt;/?)        # ratchet past optional / \n  (?:\n    [^pP]       # non-p tag\n    |           # ...or...\n    [pP][^\\s&gt;/] # longer tag that begins with p (e.g., &lt;pre&gt;)\n  )\n  [^&gt;]*         # everything until closing angled bracket\n  &gt;             # closing angled bracket\n }{}gx; # replace with nothing, globally\n</code></pre>\n\n<p>But really, save yourself some headaches and use a parser instead.  CPAN has several modules that are suitable.  Here\'s an example using the <a href="http://search.cpan.org/dist/HTML-Parser/lib/HTML/TokeParser.pm" rel="noreferrer">HTML::TokeParser</a> module that comes with the extremely capable <a href="http://search.cpan.org/dist/HTML-Parser" rel="noreferrer">HTML::Parser</a> CPAN distribution:</p>\n\n<pre><code>use strict;\n\nuse HTML::TokeParser;\n\nmy $parser = HTML::TokeParser-&gt;new(\'/some/file.html\')\n  or die "Could not open /some/file.html - $!";\n\nwhile(my $t = $parser-&gt;get_token)\n{\n  # Skip start or end tags that are not "p" tags\n  next  if(($t-&gt;[0] eq \'S\' || $t-&gt;[0] eq \'E\') &amp;&amp; lc $t-&gt;[1] ne \'p\');\n\n  # Print everything else normally (see HTML::TokeParser docs for explanation)\n  if($t-&gt;[0] eq \'T\')\n  {\n    print $t-&gt;[1];\n  }\n  else\n  {\n    print $t-&gt;[-1];\n  }\n}\n</code></pre>\n\n<p><a href="http://search.cpan.org/dist/HTML-Parser" rel="noreferrer">HTML::Parser</a> accepts input in the form of a file name, an open file handle, or a string.  Wrapping the above code in a library and making the destination configurable (i.e., not just <code>print</code>ing as in the above) is not hard.  The result will be much more reliable, maintainable, and possibly also faster (HTML::Parser uses a C-based backend) than trying to use regular expressions.</p>\n'}, {'answer_id': 30044, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 1, 'selected': False, 'text': '<p>You also might want to allow for whitespace before the "p" in the p tag. Not sure how often you\'ll run into this, but &lt; p> is perfectly valid HTML.</p>\n'}, {'answer_id': 30193, 'author': 'Jörg W Mittag', 'author_id': 2988, 'author_profile': 'https://Stackoverflow.com/users/2988', 'pm_score': 4, 'selected': False, 'text': "<p>In my opinion, trying to parse HTML with anything other than an HTML parser is just asking for a world of pain. HTML is a <em>really</em> complex language (which is one of the major reasons that XHTML was created, which is much simpler than HTML).</p>\n\n<p>For example, this:</p>\n\n<pre><code>&lt;HTML /\n  &lt;HEAD /\n    &lt;TITLE / &gt; /\n    &lt;P / &gt;\n</code></pre>\n\n<p>is a complete, 100% well-formed, 100% valid HTML document. (Well, it's missing the DOCTYPE declaration, but other than that ...)</p>\n\n<p>It is semantically equivalent to</p>\n\n<pre><code>&lt;html&gt;\n  &lt;head&gt;\n    &lt;title&gt;\n      &amp;gt;\n    &lt;/title&gt;\n  &lt;/head&gt;\n  &lt;body&gt;\n    &lt;p&gt;\n      &amp;gt;\n    &lt;/p&gt;\n  &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>But it's nevertheless valid HTML that you're going to have to deal with. You <em>could</em>, of course, devise a regex to parse it, but, as others already suggested, using an actual HTML parser is just sooo much easier.</p>\n"}, {'answer_id': 100722, 'author': 'moritz', 'author_id': 14132, 'author_profile': 'https://Stackoverflow.com/users/14132', 'pm_score': 1, 'selected': False, 'text': '<p>The original regex can be made to work with very little effort:</p>\n\n<pre><code> &lt;(?&gt;/?)(?!p).+?&gt;\n</code></pre>\n\n<p>The problem was that the /? (or \\?) gave up what it matched when the assertion after it failed. Using a non-backtracking group (?>...) around it takes care that it never releases the matched slash, so the (?!p) assertion is always anchored to the start of the tag text.</p>\n\n<p>(That said I agree that generally parsing HTML with regexes is not the way to go).</p>\n'}, {'answer_id': 2928149, 'author': 'y_nk', 'author_id': 335243, 'author_profile': 'https://Stackoverflow.com/users/335243', 'pm_score': 2, 'selected': False, 'text': "<p>I used Xetius regex and it works fine. Except for some flex generated tags which can be : <BR/> with no spaces inside. I tried ti fix it with a simple <em>?</em> after <em>\\s</em> and it looks like it's working :</p>\n\n<pre><code>&lt;(?!\\/?p(?=&gt;|\\s?.*&gt;))\\/?.*?&gt;\n</code></pre>\n\n<p>I'm using it to clear tags from flex generated html text so i also added more excepted tags :</p>\n\n<pre><code>&lt;(?!\\/?(p|a|b|i|u|br)(?=&gt;|\\s?.*&gt;))\\/?.*?&gt;\n</code></pre>\n"}, {'answer_id': 23641607, 'author': 'zx81', 'author_id': 1078583, 'author_profile': 'https://Stackoverflow.com/users/1078583', 'pm_score': 2, 'selected': False, 'text': '<p>Xetius, resurrecting this ancient question because it had a simple solution that wasn\'t mentioned. (Found your question while doing some research for a <a href="https://stackoverflow.com/q/23589174">regex bounty quest</a>.)</p>\n\n<p>With all the disclaimers about using regex to parse html, here is a simple way to do it.</p>\n\n<pre><code>#!/usr/bin/perl\n$regex = \'(&lt;\\/?p[^&gt;]*&gt;)|&lt;[^&gt;]*&gt;\';\n$subject = \'Bad html &lt;a&gt; &lt;/I&gt; &lt;p&gt;My paragraph&lt;/p&gt; &lt;i&gt;Italics&lt;/i&gt; &lt;p class="blue"&gt;second&lt;/p&gt;\';\n($replaced = $subject) =~ s/$regex/$1/eg;\nprint $replaced . "\\n";\n</code></pre>\n\n<p>See this <a href="http://ideone.com/nOLTN6" rel="nofollow noreferrer">live demo</a></p>\n\n<p><strong>Reference</strong> </p>\n\n<p><a href="https://stackoverflow.com/q/23589174">How to match pattern except in situations s1, s2, s3</a></p>\n\n<p><a href="http://www.rexegg.com/regex-best-trick.html" rel="nofollow noreferrer">How to match a pattern unless...</a></p>\n'}, {'answer_id': 66021740, 'author': 'Adebowale', 'author_id': 2088109, 'author_profile': 'https://Stackoverflow.com/users/2088109', 'pm_score': 0, 'selected': False, 'text': '<p>This works for me because all the solutions above failed for other html tags starting with p such as param pre progress, etc. It also takes care of the html attributes too.</p>\n<pre><code>~(&lt;\\/?[^&gt;]*(?&lt;!&lt;\\/p|p)&gt;)~ig\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/29869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274/']