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.
Code
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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.