Regex for HTML tags
A regular expression that finds HTML tags in simple markup, the real-world inputs that break it, and what to use instead when the HTML is not yours.
This tool runs in your browser. We never send what you type or paste to a server.
The pattern
/<\/?[a-z][^>]*>/iOn markup you wrote yourself, such as a template or a snippet you control, this finds opening, closing and self-closing tags and skips a stray < in text. It is a search pattern, so it runs with the g flag and has no anchors.
The tester at the top of this page is loaded with this pattern and the example text. Edit either box to try your own.
How it works, token by token
| Part | Meaning |
|---|---|
< | A literal opening angle bracket. |
\/? | An optional slash, for closing tags such as </p>. |
[a-z] | A letter, which every tag name starts with. This is what stops 3 < 5 from matching. The i flag allows capitals. |
[^>]* | Anything up to the next >: the rest of the name, attributes and a self-closing slash. |
> | The closing angle bracket. |
What it finds
Searching this text:
<p class="intro">Hello <b>world</b>!<br/></p> 3 < 5finds 5 matches:
1. <p class="intro">
2. <b>
3. </b>
4. <br/>
5. </p>
Where it breaks
A > is allowed inside a quoted attribute value, and the pattern stops at the first one:
/<\/?[a-z][^>]*>/iSearching this text:
<a title="1 > 0" href="/x">link</a>finds 2 matches:
1. <a title="1 >
2. </a>Comments and scripts are worse. The tags inside a comment are not tags at all, and the text of a script is not HTML, but the pattern cannot know either:
/<\/?[a-z][^>]*>/iSearching this text:
<!-- <b>old</b> --><script>if (a<b) go()</script>finds 4 matches:
1. <b>
2. </b>
3. <script>
4. <b) go()</script>Each failure can be patched (handle quotes, skip comments, special-case <script> and <style>), and each patch makes the pattern longer without making it right.
Why you cannot parse HTML with a regex
Regular expressions recognise flat patterns. HTML is a tree: elements nest inside each other to any depth, and matching each closing tag to its opening tag needs a stack, which a regular expression does not have. On top of that, real HTML is forgiving by design. The HTML parsing algorithm in the standard says exactly how browsers recover from missing end tags, misnested elements and unquoted attributes, and a <p> is closed implicitly by the next block element. A regex that disagrees with the browser about where an element ends will sooner or later read the wrong text.
Use a parser
Every platform has one. In the browser, DOMParser builds a document from a string without running its scripts, and textContent gives you the text. Python's standard library has html.parser:
from html.parser import HTMLParser
class TextOnly(HTMLParser):
def __init__(self):
super().__init__()
self.parts = []
def handle_data(self, data):
self.parts.append(data)
p = TextOnly()
p.feed('<p title="1 > 0">Fish & <b>chips</b></p>')
print(''.join(p.parts)) # → Fish & chipsIt handles the > in the attribute and turns & into &, which the regex version does not:
/<[^>]*>/g| Input | Output |
|---|---|
<p>Fish & <b>chips</b></p> | Fish & chips |
<a title="1 > 0">x</a> | ␣0">x |
PHP has DOMDocument. .NET has no HTML parser in its base library, so C# projects usually add a package such as AngleSharp or HtmlAgilityPack.
Never use a regex to make untrusted HTML safe to display. Removing <script> tags misses event attributes, javascript: links and many other routes. Use a sanitiser built on a real parser, such as DOMPurify, or escape the text so it is never treated as HTML at all, as the HTML entity encoder does.
In JavaScript, Python, PHP and C#
JavaScript
const text = '<p class="intro">Hello <b>world</b>!<br/></p> 3 < 5';
for (const m of text.matchAll(/<\/?[a-z][^>]*>/ig)) console.log(m[0]);
// → <p class="intro">
// → <b>
// → </b>
// → <br/>
// → </p>
Python
import re
text = '<p class="intro">Hello <b>world</b>!<br/></p> 3 < 5'
for m in re.finditer(r'</?[a-z][^>]*>', text, flags=re.IGNORECASE):
print(m.group())
# → <p class="intro">
# → <b>
# → </b>
# → <br/>
# → </p>
PHP
<?php
$text = '<p class="intro">Hello <b>world</b>!<br/></p> 3 < 5';
preg_match_all('/<\/?[a-z][^>]*>/i', $text, $m);
foreach ($m[0] as $match) echo $match, "\n";
// → <p class="intro">
// → <b>
// → </b>
// → <br/>
// → </p>
C#
using System;
using System.Text.RegularExpressions;
var text = "<p class=\"intro\">Hello <b>world</b>!<br/></p> 3 < 5";
foreach (Match m in Regex.Matches(text, @"</?[a-z][^>]*>", RegexOptions.IgnoreCase)) Console.WriteLine(m.Value);
// → <p class="intro">
// → <b>
// → </b>
// → <br/>
// → </p>Python's re.findall returns the capture groups instead of the whole match when a pattern has groups, so re.finditer is the safer habit. In PHP, preg_match_all puts the whole matches in $m[0].
The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.
Questions
What is the regex for an HTML tag?
<\/?[a-z][^>]*> with the i and g flags finds opening, closing and self-closing tags in simple markup. It fails on a > inside an attribute value, and treats tags in comments and scripts as real.
How do I strip HTML tags with a regex?
Replacing <[^>]*> with nothing works on simple, trusted markup, but leaves entities such as & encoded and breaks on a > inside an attribute. Use a parser and read the text content instead.
Can I use a regex to remove script tags for security?
No. There are many ways to run script without a script tag, such as onerror attributes. Use a sanitiser like DOMPurify, or escape the text.