实现说明
除了类 LogFieldExtractor和函数 extractBetween、main,文件里再无其他定义。
使用要点
- 演示输出是带标签的(
level:、module:、trace:),每个操作都会留下自己的一行标注。 main的演示流程是extractBetween——跑一遍文件,这条流程从头到尾可见。
常见问题
运行「indexOf 提取分隔符之间的值」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 level:、module:、trace: 标签标明各步骤。
主签名形如 static String extractBetween(String line, String key)
核心语句
return null; // a missing key is the caller's semantic decision
}
return line.substring(valueAt, end);
代码示例
public class LogFieldExtractor {
// Lines look like [2026-11-18 09:15:02] level=INFO module=auth message="login ok"
// Extract the value between key= and the next space: indexOf locates, substring cuts
static String extractBetween(String line, String key) {
int keyAt = line.indexOf(key + "=");
if (keyAt < 0) {
return null; // a missing key is the caller's semantic decision
}
int valueAt = keyAt + key.length() + 1;
int end = line.indexOf(' ', valueAt);
if (end < 0) {
end = line.length();
}
return line.substring(valueAt, end);
}
public static void main(String[] args) {
String line = "[2026-11-18 09:15:02] level=INFO module=auth message=\"login ok\"";
System.out.println("level: " + extractBetween(line, "level"));
System.out.println("module: " + extractBetween(line, "module"));
System.out.println("trace: " + extractBetween(line, "trace"));
// Quoted values containing spaces need a different terminator: find the opening quote, take the rest of the line, then strip the quote
int valueAt = line.indexOf("message=\"") + "message=\"".length();
System.out.println("message: " + line.substring(valueAt, line.length() - 1));
}
}