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

Extracting Structured Data with Named Groups

Parse structured text like dates, URLs, or log entries by extracting components into clearly-named groups.

Extracting Structured Data with Named Groups

You'll learn how to parse structured text like dates, URLs, or log entries by extracting components into clearly-named groups for cleaner, more maintainable code.

The Core Idea

Instead of remembering that "group 2 is the month" or "group 5 is the port number," named groups let you extract data using meaningful labels. This transforms regex from a cryptic indexing exercise into self-documenting parsing code. When dealing with structured formats like dates (2024-03-15), URLs (https://example.com:8080/path), or log entries, named groups make your extraction logic readable and less error-prone.

Practical Example: Parsing a Date

import java.util.regex.*;

String text = "Event occurred on 2024-03-15 at noon";
Pattern pattern = Pattern.compile("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})");
Matcher matcher = pattern.matcher(text);

if (matcher.find()) {
    String year = matcher.group("year");    // "2024"
    String month = matcher.group("month");  // "03"
    String day = matcher.group("day");      // "15"
    
    System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day);
}

Parsing URLs with Multiple Components

String url = "https://api.example.com:8080/users";
Pattern urlPattern = Pattern.compile(
    "(?<protocol>https?)://(?<host>[^:]+):(?<port>\\d+)(?<path>/.*)");
Matcher urlMatcher = urlPattern.matcher(url);

if (urlMatcher.matches()) {
    String protocol = urlMatcher.group("protocol");  // "https"
    String host = urlMatcher.group("host");          // "api.example.com"
    String port = urlMatcher.group("port");          // "8080"
    String path = urlMatcher.group("path");          // "/users"
}

Think of named groups as labeling boxes when unpacking a shipment—instead of "box 1, box 2, box 3," you have "electronics," "books," "clothing."

Key Takeaway: Named groups transform regex from cryptic number-based extraction into self-documenting, readable parsing code—essential for handling structured formats like dates, URLs, and log files where clarity matters as much as correctness.