HTML Tag Regex

<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>

Match HTML tags with their content. Captures tag name and inner content.

Test This Pattern →

Pattern Breakdown

Understanding the regex pattern <([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>:

  • ^ - Start of string
  • .* - Any character, zero or more times
  • ? - Optional (zero or one)
  • * - Zero or more
  • [...] - Character class
  • (...) - Capturing group

Examples

Input Result Explanation
<div>content</div> ✓ Match Simple div tag
<p class="text">Hello</p> ✓ Match Tag with attribute

Code Examples

JavaScript

JavaScript
const pattern = /<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\\/\1>/;
const text = "<div>content</div>";

// Test if string matches
if (pattern.test(text)) {
  console.log("Valid!");
}

// Extract matches
const matches = text.match(pattern);
console.log(matches);

Python

Python
import re

pattern = r'<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>'
text = "<div>content</div>"

# Test if string matches
if re.match(pattern, text):
    print("Valid!")

# Find all matches
matches = re.findall(pattern, text)
print(matches)

PHP

PHP
<?php
$pattern = '/<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\\/\1>/';
$text = "<div>content</div>";

// Test if string matches
if (preg_match($pattern, $text)) {
    echo "Valid!";
}

// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>

Java

Java
import java.util.regex.*;

String pattern = "<([a-z][a-z0-9]*)\\b[^>]*>(.*?)<\\/\\1>";
String text = "<div>content</div>";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);

if (m.matches()) {
    System.out.println("Valid!");
}

Use Cases

Common applications: HTML parsing, template engines, sanitization

Frequently Asked Questions

What is the regex pattern for html tag regex?
The regex pattern is: <([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>. Match HTML tags with their content. Captures tag name and inner content.
How do I use the html tag regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('<([a-z][a-z0-9]*)\\b[^>]*>(.*?)<\\/\\1>'); or const regex = /<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\\/\1>/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>') in Python. Most regex patterns are cross-language compatible.
What are common use cases for html tag regex?
HTML parsing, template engines, sanitization

Related Regex Patterns

More Regex Tools

GetDevUtils offers a suite of developer tools including: