T
ToolPrime

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
&lt;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

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.

Related Tools