Java字符串查找应据需选用方法:基础子串用indexOf()并判-1;复杂模式用Pattern+Matcher;存在性判断可用contains();大文件须流式读取并指定编码。
Java 自带的字符串查找能力足够应付大多数文本查找场景,不需要额外引入框架——关键在于选对方法、避开边界陷阱。
String.indexOf() 做基础子串定位这是最常用也最容易误用的方法。它返回首次匹配的起始索引,没找到时返回 -1,但不会抛异常,所以必须显式判断。
"Hello".indexOf("hello") 返回 -1
str.indexOf("abc", 3)
"\\d[a-z]",会按字面量找String text = "error: invalid port, retrying...";
int pos = text.indexOf("port");
if (pos != -1) {
System.out.println("found at index " + pos); // 输出:found at index 13
}
Pattern + Matcher 处理复杂模式当要查找手机号、邮箱、日志级别(ERROR|WARN|INFO)或带上下文的文本时,必须上正则。注意别直接用 String.matches()——它要求**整串匹配**,不适合查找子串。
Pattern.compile(regex).matcher(text) 获取 Matcher 实例find() 循环匹配,再用 start()/end() 取位置Pattern 提成 static final 字段Matcher 不是线程安全的,多线程共用一个实例会出错Pattern p = Pattern.compile("\\bERROR\\b");
Matcher m = p.matcher("ERROR occurred at line 42. WARN ignored.");
while (m.find()) {
Sys
tem.out.printf("'%s' at %d–%d%n", m.group(), m.start(), m.end());
// 输出:'ERROR' at 0–5
}
contains() 和 indexOf() > -1
两者语义相同,都判断是否存在子串,但行为有细微差别:
contains() 是 Java 7+ 加入的语法糖,底层就是调 indexOf() >= 0
contains() 更可读;如果后续还需要位置信息,直接用 indexOf() 避免重复调用str.toLowerCase().contains(target.toLowerCase()),但要注意 locale 问题(如土耳其语的 i 转换异常)Files.readAllLines()
处理大文件(比如几百 MB 的日志)时,一次性读进内存会 OOM。应使用流式读取 + 即时匹配:
Files.lines(path) 返回 Stream,配合 filter() 和 findFirst()
BufferedReader + readLine(),边读边判断,内存占用恒定StandardCharsets.UTF_8
try (Streamlines = Files.lines(Paths.get("app.log"), StandardCharsets.UTF_8)) { Optional firstError = lines .filter(line -> line.contains("ERROR")) .findFirst(); firstError.ifPresent(System.out::println); }
真正难的不是写查找逻辑,而是明确“查什么”——是精确词、模糊前缀、正则片段,还是跨行上下文?不同目标对应不同 API 组合,混用或硬套一种方式反而让代码更脆弱。