// 基础编译 Pattern emailPattern = Pattern.compile("\w+@\w+\.\w+");
// 带标志的编译 - 忽略大小写 Pattern caseInsensitivePattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
// 错误的做法 - 每次都要重新编译 for (String log : logs) {
if (log.matches(".*ERROR.*")) {
// 处理错误日志
}
}
// 正确的做法 - 一次编译,多次使用 Pattern errorPattern = Pattern.compile(".ERROR."); for (String log : logs) {
Matcher matcher = errorPattern.matcher(log);
if (matcher.matches()) {
// 处理错误日志
}
}
// 性能杀手 for (String input : inputs) {
Pattern.compile(regex).matcher(input).matches();
}
// 正确做法 Pattern pattern = Pattern.compile(regex); for (String input : inputs) {
pattern.matcher(input).matches();
}
