Regex for HTML Tag
Matches HTML tags including opening, closing, and self-closing tags.
Pattern
/<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/?>/g Live Tester
Enter a string to test
Examples
The g flag makes the pattern apply special matching behavior and match globally.
✓ <div>
✓ </p>
✓ <img src="test.jpg" />
✗ < div>
✗ plain text
✗ <not a tag
Pattern Breakdown
< — opening angle bracket
\/? — optional forward slash
[a-zA-Z][a-zA-Z0-9]* — tag name
(?:\s[^>]*)? — optional attributes
\/?> — optional self-closing + closing bracket
Code Snippets
Javascript
const regex = /<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/??>/g;
"<div>text</div>".match(regex); // ["<div>", "</div>"] Python
import re
pattern = r"</?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/?>"
re.findall(pattern, "<div>text</div>") # ['<div>', '</div>'] Php
$pattern = '/<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/??>/';
preg_match_all($pattern, "<div>text</div>", $matches); Related Patterns
Email Address /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ URL /^https?:\/\/(www\.)?[a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([a-zA-Z0-9()@:%_+.~#?&/=-]*)$/ Username /^[a-zA-Z][a-zA-Z0-9_-]{2,19}$/ URL Slug /^[a-z0-9]+(-[a-z0-9]+)*$/ File Extension /\.[a-zA-Z0-9]{1,10}$/ Domain Name /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/
Frequently Asked Questions
What is the regex for HTML Tag?▾
The regex pattern for HTML Tag is /<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/?>/g. Matches HTML tags including opening, closing, and self-closing tags.
How do I use the HTML Tag regex in JavaScript?▾
In JavaScript you create the pattern with a regex literal or the RegExp constructor and call .test() to check a string against it. A ready-to-copy example is shown in the Code Snippets section above, alongside Python and PHP versions.
What does the HTML Tag pattern match?▾
It matches strings like <div>; it rejects strings like < div>. See the Examples section above for the full list of matching and non-matching cases.