Match opening and closing HTML tags including self-closing tags using regex. Extract tag names, attributes, and content.
/<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/?>/g| Token | Meaning |
|---|---|
< | Opening angle bracket |
\/? | Optional forward slash (for closing tags) |
[a-zA-Z] | Tag name must start with a letter |
[a-zA-Z0-9]* | Rest of tag name (letters and digits) |
(?:\s[^>]*)? | Optional attributes (space followed by non-closing bracket characters) |
\/?> | Optional self-closing slash and closing bracket |
<div>Match</div>Match<br/>Match<img src="x.png" />Match<p class="text">Matchplain textNo match< notag>No matchconst htmlTagRegex = /<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/?>/ g;
const html = '<div class="test"><p>Hello</p><br/></div>';
const matches = html.match(htmlTagRegex);
console.log(matches); // ["<div class=\"test\">", "<p>", "</p>", "<br/>", "</div>"]import re
html_tag_regex = r'</?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/? >'
html = '<div class="test"><p>Hello</p><br/></div>'
matches = re.findall(html_tag_regex, html)
print(matches) # ['<div class="test">', '<p>', '</p>', '<br/>', '</div>']Want to test this pattern with your own data?
Try this pattern in Regex Tester →