Regex Named Capturing Groups

Extract structured fields from log lines and email addresses with named capturing groups, reading each match by name instead of fragile numbered group indexes.

JavaData Integrity

Code

snippet
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogLineParser {

    // 具名捕获组 (?<name>...):按语义命名,不依赖脆弱的数字下标
    private static final Pattern LOG_LINE = Pattern.compile(
            "(?<timestamp>[0-9T:-]+) (?<level>[A-Z]+) (?<message>.*)");

    public static void main(String[] args) {
        String line = "2026-11-14T09:30:00 ERROR Order 42 payment timed out";
        Matcher matcher = LOG_LINE.matcher(line);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("unrecognized log line: " + line);
        }

        System.out.println("timestamp = " + matcher.group("timestamp"));
        System.out.println("level     = " + matcher.group("level"));
        System.out.println("message   = " + matcher.group("message"));

        // 多次匹配场景:每次 find() 后都能按名字取组
        Pattern contacts = Pattern.compile("(?<user>[A-Za-z.]+)@(?<host>[a-z]+[.][a-z]{2,})");
        Matcher emails = contacts.matcher("[email protected], [email protected]");
        while (emails.find()) {
            System.out.println(emails.group("user") + " at " + emails.group("host"));
        }
    }
}

How the snippet works

Regex Named Capturing Groups keeps everything in the class LogLineParser and the function main.

The one repetition in this snippet is the loop while (emails.find()). The failure path is explicit — IllegalArgumentException is raised when the guard condition holds.

Applying it

The demo output is labeled (timestamp =, level =, message =), so every printed line maps back to its originating operation.

Statements that matter

throw new IllegalArgumentException("unrecognized log line: " + line);

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
The code refuses to continue: `IllegalArgumentException` is thrown while the state is still recoverable.
What does Regex Named Capturing Groups print when run?
No setup needed: run the file and look for labeled lines like `timestamp =`, `level =`, `message =` in the output.