← 中文资源

简体中文版本

正则 flag 组合:行锚定与大小写

MULTILINE 让 ^ 和 $ 按行锚定,CASE_INSENSITIVE 折叠大小写(非 ASCII 需叠加 UNICODE_CASE),DOTALL 让点号跨行匹配;多个 flag 用位或组合。

阅读英文原文

实现说明

真正干活的是类 LogPatternScanner和函数 main、count,其余都是接线。 文件的主干是一个循环——while (matcher.find())。

使用要点

  • 跑完文件,输出里会留下标记——plain ^WARN hits:、multiline ^WARN hits:、insensitive warn hits:。
  • main 的演示流程是 count——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「正则 flag 组合:行锚定与大小写」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 plain ^WARN hits:、multiline ^WARN hits:、insensitive warn hits: 标签标明各步骤。

核心语句

+ Pattern.compile("^warn.*full$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE)
        .matcher(log).find());
String log = "WARN disk almost full\nINFO deploy ok\nWARN cache thrashing";
int hits = 0;

代码示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogPatternScanner {

    public static void main(String[] args) {
        String log = "WARN disk almost full\nINFO deploy ok\nWARN cache thrashing";

        // 无 MULTILINE:^ 只锚定整段输入的开头
        System.out.println("plain ^WARN hits:      "
                + count(Pattern.compile("^WARN").matcher(log)));

        // MULTILINE:^ / $ 改为按行锚定,两行 WARN 都命中
        System.out.println("multiline ^WARN hits:  "
                + count(Pattern.compile("^WARN", Pattern.MULTILINE).matcher(log)));

        // CASE_INSENSITIVE:大小写折叠;默认只覆盖 ASCII,非 ASCII 需叠加 UNICODE_CASE
        System.out.println("insensitive warn hits: "
                + count(Pattern.compile("warn", Pattern.CASE_INSENSITIVE).matcher(log)));

        // DOTALL:让点号吞掉换行,跨行匹配
        System.out.println("dotall full...ok:      "
                + Pattern.compile("full.*ok", Pattern.DOTALL).matcher(log).find());

        // 多个 flag 用位或组合
        System.out.println("combo per-line:        "
                + Pattern.compile("^warn.*full$", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE)
                        .matcher(log).find());
    }

    private static int count(Matcher matcher) {
        int hits = 0;
        while (matcher.find()) {
            hits++;
        }
        return hits;
    }
}