实现说明
正则具名捕获组可以归结为类 LogLineParser和函数 main。
迭代发生在 while (emails.find()) 内部——循环之外的语句只执行一遍。IllegalArgumentException 之前有一道守卫:坏状态在这里就停下,不会继续往下走。
使用要点
- 演示输出是带标签的(
timestamp =、level =、message =),每个操作都会留下自己的一行标注。
常见问题
遇到格式错误的数据会怎样?
代码会拒绝继续:抛出 IllegalArgumentException,此时状态仍可恢复。
运行「正则具名捕获组」会打印什么?
整个文件跑完,输出行以 timestamp =、level =、message = 这类前缀开头。
核心语句
throw new IllegalArgumentException("unrecognized log line: " + line);
代码示例
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"));
}
}
}