Course contentsShow
← Java
Lesson 2290 of 2,87044. Regular ExpressionsFree lesson

HTML Tag Matching and Extraction

Write patterns to match opening tags, closing tags, self-closing tags, and extract tag content.

HTML Tag Matching and Extraction

You'll learn how to write regular expressions that match HTML tags and extract their names, attributes, and content.

The Core Idea

HTML tags follow predictable patterns: opening tags like <div>, closing tags like </div>, self-closing tags like <br/>, and tags with attributes like <a href="url">. Regular expressions can identify these structures and extract their components using capturing groups.

Think of HTML parsing like recognizing the parts of a sentence. Just as you can identify subjects, verbs, and objects, regex lets you identify tag names, attributes, and the content between tags.

Common HTML Tag Patterns

Opening tags:

Pattern openTag = Pattern.compile("<([a-zA-Z][a-zA-Z0-9]*)\\s*([^>]*)>");

This captures the tag name in group 1 and attributes in group 2.

Closing tags:

Pattern closeTag = Pattern.compile("</([a-zA-Z][a-zA-Z0-9]*)>");

Group 1 captures the tag name.

Self-closing tags:

Pattern selfClosing = Pattern.compile("<([a-zA-Z][a-zA-Z0-9]*)\\s*([^>]*)/>");

Extracting content between matching tags:

Pattern contentPattern = Pattern.compile("<(\\w+)>([^<]+)</\\1>");
// Group 1: tag name, Group 2: content
// \\1 is a backreference ensuring closing tag matches opening tag

Practical Example

String html = "<p>Hello</p><div id='main'>Content</div><br/>";
Pattern pattern = Pattern.compile("<(\\w+)(?:\\s+[^>]*)?>([^<]*)</\\1>");
Matcher matcher = pattern.matcher(html);

while (matcher.find()) {
    String tagName = matcher.group(1);
    String content = matcher.group(2);
    System.out.println(tagName + ": " + content);
}

Note: These patterns work for simple HTML. Real-world HTML parsing requires dedicated parsers due to nested tags, malformed markup, and complex edge cases.

Key Takeaway: Use capturing groups to extract tag names, backreferences to match paired tags, and non-capturing groups for optional attributes when writing HTML tag patterns.