DevTools
Back to Regex Tester

HTML Tag Regex Pattern

Match opening and closing HTML tags including self-closing tags using regex. Extract tag names, attributes, and content.

The Pattern

/<\/?[a-zA-Z][a-zA-Z0-9]*(?:\s[^>]*)?\/?>/g

How It Works

TokenMeaning
<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

Test Cases

<div>Match
</div>Match
<br/>Match
<img src="x.png" />Match
<p class="text">Match
plain textNo match
< notag>No match

Code Examples

javascript
const 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>"]
python
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>']

Common Use Cases

Related Patterns

Want to test this pattern with your own data?

Try this pattern in Regex Tester →