Featured image of post 正则表达式实战:日志分析里的十个高频用法

正则表达式实战:日志分析里的十个高频用法

以日志分析为主线,整理正则的十个高频场景:提取 IP、解析堆栈、清洗 ANSI 转义、匹配多行日志、校验 UUID、批量重命名、脱敏手机号,以及正则回溯导致的 ReDoS 陷阱。

43 次

问题现场

一个 8G 的日志文件,要找出所有超时请求的 traceId:

grep "TimeoutException" app.log

输出了 12 万行,其中大部分是多行堆栈。真正要的是行首那些带 traceId 的:

grep -oP 'traceId=\K[a-f0-9]{32}' app.log | sort -u

跑了两分钟才出结果。后来发现日志里有巨量 ANSI 转义符和多行堆栈,正则的性能问题被放大了。

这篇把日志分析场景下真正会用到的正则技巧整理一遍,附性能对比。

先说性能:为什么正则会卡死

一个真实的 ReDoS

// 危险:嵌套量词
String pattern = "^(a+)+$";
System.out.println(pattern.matches("aaaaaaaaaaaaaaaaaaaaaaaaX"));
// 结果:跑了几分钟没出来,最后 StackOverflowError

原因:当末尾字符匹配不上时,引擎会回溯所有可能的分组方式。

输入  aaaaaaaaaaaaaaaaaaaaaaaaX
匹配  ^(a+)+$
      ↑      ↑
      1 个 a   2 个 a   3 个 a  ...  24 个 a   ← 2^24 种组合
      最后要匹配 X,但输入里没有
      → 回溯遍历所有组合,全失败

这叫灾难性回溯(Catastrophic Backtracking)。

三个防御手段

1. 避免嵌套量词
   ✗ (a+)+     → 回溯指数级
   ✓ a+        → 线性

2. 避免相邻的可重叠量词
   ✗ a*a*
   ✗ \s*\s*
   ✓ \s+

3. Java 用超时保护
   Pattern.compile(pattern).matcher(input).matches()
   → 改成带超时的方式
/**
 * 带超时的正则匹配。
 * 用独立线程 + Future,超时就中断。
 */
public static boolean matchesSafely(String regex, CharSequence input,
                                     long timeoutMs) {
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(input);

    ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r, "regex-timeout");
        t.setDaemon(true);
        return t;
    });

    try {
        Future<Boolean> future = executor.submit(() -> m.matches());
        return future.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        m.reset();
        future.cancel(true);
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        executor.shutdownNow();
    }
}

更好的方案是别用正则。有些场景用 String.indexOf / split 性能差几个数量级:

// ✗ 正则
Pattern.compile(",").split(input);

// ✓ 手工切分(快 5-10 倍)
splitFast(input, ',');

场景一:提取 IP 地址

# 从日志里提取所有客户端 IP
grep -oP 'clientIp=\K[\d.]+' app.log | sort | uniq -c | sort -rn | head -20
private static final Pattern IP_PATTERN = Pattern.compile(
    "(?<=clientIp=)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");

\K 的作用:告诉正则「只匹配这之后的部分」。比写捕获组再取 group(1) 更直接。

# 也可以不用 \K,用捕获组
grep -oP 'clientIp=(\d+\.\d+\.\d+\.\d+)' app.log | cut -d= -f2

性能对比(8G 日志):

grep 'clientIp' | awk '{print $3}'   → 38s   (格式固定时最快)
grep -oP 'clientIp=\K[\d.]+'          → 72s
grep -oP '\d+\.\d+\.\d+\.\d+'         → 145s  (不限定前缀,慢一倍)

教训:正则越「精确」,引擎越容易提前结束匹配。clientIp= 前缀把候选位置砍掉了一大半。

场景二:解析异常堆栈

Java 堆栈的关键是取第一行(异常类型和消息)和第一帧(出错的位置)。

# 从混合日志里提取所有异常的第一行
grep -A1 '^\s*at ' app.log | grep -v '^\s*at ' | grep -v '^--' | sort | uniq -c | sort -rn | head
/**
 * 从堆栈文本中提取「异常类型 + 出错位置 + 行号」。
 *
 * 典型输入:
 *   java.lang.NullPointerException: Cannot read field "id"
 *       at com.example.OrderService.find(OrderService.java:88)
 *       at ...
 */
public class StackTraceParser {

    // 第一行:异常全名 + 消息
    private static final Pattern HEADER = Pattern.compile(
        "^(?:[\\w$]+\\.)*(\\w+(?:Exception|Error|Throwable))"
        + "(?::\\s*(.*))?$");

    // at com.example.Foo.bar(Foo.java:88)
    private static final Pattern FRAME = Pattern.compile(
        "\\s*at\\s+([\\w$.]+)\\.([\\w$<>]+)\\((\\w+\\.java):(\\d+)\\)");

    public static ParsedError parse(String[] lines) {
        ParsedError result = new ParsedError();

        for (String line : lines) {
            if (result.exceptionType == null) {
                Matcher h = HEADER.matcher(line.trim());
                if (h.matches()) {
                    result.exceptionType = h.group(1);
                    result.message = h.group(2);
                    continue;
                }
            }
            if (result.topFrame == null) {
                Matcher f = FRAME.matcher(line);
                if (f.find()) {
                    result.topFrame = f.group(1) + "." + f.group(2);
                    result.fileName = f.group(3);
                    result.lineNumber = Integer.parseInt(f.group(4));
                }
            }
        }
        return result;
    }
}

输出示例:

java.lang.NullPointerException: Cannot read field "id"
  → com.example.OrderService.find
  → OrderService.java:88
  出现次数:37

这个聚合结果直接就是「本周要修的问题清单」。

场景三:清洗 ANSI 转义符

带颜色输出的日志,用编辑器看是一堆乱码:

# 去掉所有 ANSI 转义序列
sed -r 's/\x1B\[[0-9;]*[mGKHF]//g' app.log > clean.log

# 一行完成管道处理
cat app.log | perl -pe 's/\e\[[0-9;]*[a-zA-Z]//g' > clean.log
import re

ANSI_ESCAPE = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')

def strip_ansi(text: str) -> str:
    """清除 ANSI 转义序列,让日志可用于文本分析。"""
    return ANSI_ESCAPE.sub('', text)

正则解释:

\x1B               ESC 字符
(?:[@-Z\\-_]        单字符转义序列
  |\[[0-?]*[ -/]*[@-~])   CSI 序列(颜色、光标控制)

注意 [0-?] 用的是 ?(0x3F)不是字面问号 —— 这是 ECMA-48 定义的字符范围,写成 0-9; 是简化版,遇到某些序列会漏。

private static final Pattern ANSI = Pattern.compile(
    "\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])");

顺带:日志里还有 \r(Windows 换行)和零宽字符,一并清掉:

sed -r 's/\x1B\[[0-9;]*[mGKHF]//g; s/\r$//; s/\x00//g' app.log

场景四:匹配多行日志

有些异常堆栈是多行的,逐行 grep 会漏。

# pcregrep 支持跨行匹配(grep -P 不支持)
pcregrep -M 'NullPointerException[\s\S]{0,500}' app.log

# 或者先合并多行,再匹配
awk '/^[0-9]{4}-[0-9]{2}-[0-9]{2}/{buf=""} {buf=buf"\n"$0} END{print buf}' app.log \
  | grep -A20 'NullPointerException'
// Java: DOTALL 模式让 . 匹配换行
Pattern p = Pattern.compile(
    "ERROR.*?Caused by:\\s*(.*)", Pattern.DOTALL);

DOTALL 的性能代价:. 可以匹配换行会让回溯空间指数增长。只在必要处用,或者改用非贪婪 + 限定长度:

// 比 DOTALL 更安全的写法
Pattern.compile("ERROR(.{0,2000}?)Caused by:\\s*(.*)", Pattern.DOTALL);

注意 (?s) 是 DOTALL,(?m) 是 MULTILINE(^ $ 匹配每行),两个经常搞混:

(?s)  DOTALL     .  能匹配 \n
(?m)  MULTILINE  ^ 和 $ 匹配每行的开始/结束
(?x)  扩展模式   忽略空白和 # 注释 ← 写复杂正则时很好用
// (?x) 模式让复杂正则可读
Pattern.compile("""
    ^(?<level>ERROR|WARN)\s+          # 级别
    \[(?<ts>[\d\-T:]+)\]\s+           # 时间
    \[(?<traceId>[a-f0-9]{32})\]      # traceId
    \s+(?<msg>.+)$                    # 消息
    """, Pattern.COMMENTS | Pattern.UNICODE_CASE);

(?x) 模式在写复杂正则时价值极大 —— 可以加注释、可以换行,几乎能当代码读。

场景五:日志格式解析(命名捕获组)

/**
 * 用命名捕获组解析日志行,比数字索引好维护得多。
 *
 * 日志格式:2026-10-15T22:30:45.123 ERROR [traceId=xxx] 连接池耗尽
 */
private static final Pattern LOG_LINE = Pattern.compile("""
    (?<ts>\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3})
    \\s+(?<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)
    \\s+\\[traceId=(?<traceId>[a-f0-9]{32})\\]
    (?<thread>[\\w\\-.]+)
    \\s+(?<message>.+)
    """, Pattern.COMMENTS);

public LogEntry parse(String line) {
    Matcher m = LOG_LINE.matcher(line);
    if (!m.matches()) {
        return null;
    }
    return new LogEntry(
        m.group("ts"),
        m.group("level"),
        m.group("traceId"),
        m.group("thread"),
        m.group("message"));
}
命名组 vs 数字组的区别:

数字组:
  m.group(1)  // 忘了前面加了个组,位置全错,且无法自解释

命名组:
  m.group("traceId")   // 自解释,重构时不会错

正则重构时的价值:往中间插一个新组,所有数字索引都会错位,但命名组不受影响。

场景六:脱敏

日志里的敏感信息必须脱敏后才能外发。

public class LogSanitizer {

    private static final List<Pattern> SENSITIVE_PATTERNS = Arrays.asList(
        // 手机号(保留前3后4)
        compile("(?<!\\d)(1[3-9]\\d)(\\d{4})(\\d{4})(?!\\d)", "$1****$3"),

        // 身份证(保留前6后4)
        compile("(?<!\\d)(\\d{6})\\d{8}([\\dXx]{4})(?!\\d)", "$1********$2"),

        // 银行卡(保留后4)
        compile("(?<!\\d)(\\d{4})\\d{11}(\\d{4})(?!\\d)", "$1***********$2"),

        // 邮箱
        compile("([\\w.+-]+)@([\\w-]+\\.[\\w.]+)", "$1***@$2"),

        // 访问密钥
        compile("(?i)(access[_-]?key|secret|password|token)"
                + "\\s*[=:]\\s*['\"]?([\\w\\-]{16,})",
                "$1=$2"),

        // 身份证/银行卡混排时容易误伤,加边界断言
        compile("(?<!\\d)(\\d{19})(?!\\d)", "***************")
    );

    public static String sanitize(String text) {
        String result = text;
        for (int i = 0; i < SENSITIVE_PATTERNS.size(); i++) {
            Pattern p = SENSITIVE_PATTERNS.get(i);
            Matcher m = p.matcher(result);
            result = m.replaceAll(p.pattern().startsWith("(") ? "$0" : m.groupCount() > 0 ? "$0" : "$0");
        }
        return result;
    }
}

更清晰的写法(每条规则独立处理):

private static final Map<String, Pattern> RULES = new LinkedHashMap<>();

static {
    RULES.put("手机号", Pattern.compile("(?<!\\d)(1[3-9]\\d\\d{4})\\d{4}(?!\\d)"));
    RULES.put("身份证", Pattern.compile("(?<!\\d)(\\d{6})\\d{8}(\\d{4}[\\dXx])(?!\\d)"));
    RULES.put("邮箱",   Pattern.compile("([\\w.+-]{2})[\\w.+-]*(@[\\w-]+\\.[\\w.]+)"));
    RULES.put("密钥",   Pattern.compile("(?i)((?:access[_-]?key|secret|password|token)"
                                      + "\\s*[=:]\\s*['\"]?)([\\w\\-]{16,})"));
}

public static String sanitize(String text) {
    String r = text;
    r = replaceAll(r, RULES.get("手机号"), "$1****");
    r = replaceAll(r, RULES.get("身份证"), "$1********$2");
    r = replaceAll(r, RULES.get("邮箱"),   "$1***$2");
    r = replaceAll(r, RULES.get("密钥"),   "$1******");
    return r;
}

private static String replaceAll(String input, Pattern p, String repl) {
    return p.matcher(input).replaceAll(repl);
}

正则里的关键技巧:负向前瞻/后顾断言。

(?<!\\d)   左边不能是数字
(?!\\d)    右边不能是数字

为什么必须加:不加的话,138001380001234(一个长数字)里的子串会被误判成手机号。加了边界断言,只匹配独立的 11 位数字。

测试:

// ✓ 应该脱敏
sanitize("用户 13800138000 登录");    → "用户 1380013800* 登录"(不对,实际应该 138****8000)

// ✗ 不应该被脱敏(是订单号)
sanitize("订单 20261015000123456");  → "订单 20261015000123456"

所以手机号规则应该分成两个捕获组:

Pattern.compile("(?<!\\d)(1[3-9]\\d)(\\d{4})(\\d{4})(?!\\d)")
//                        ↑前3      ↑中间4    ↑后4
// 替换:$1****$3

场景七:批量重命名(用正则提取数字排序)

# 把 screenshot(1).png 这种带编号的文件按数字排序
for f in $(ls *.png | grep -oP '\d+(?=\.png$)' | sort -n); do
    echo "序号 $f"
done

# 更实用的:按文件内容里的数字排序并批量重命名
ls | grep -P '^\d+' | sort -t- -k1 -n | while read f; do
    num=$(echo "$f" | grep -oP '^\d+')
    mv "$f" "$(printf '%04d' "$num")-$(echo "$f" | cut -d- -f2-)"
done
# 用 sed 提取文件名中的日期并用于排序(日志归档常用)
ls /var/log/app/ | grep -oP '\d{4}-\d{2}-\d{2}' | sort

实用组合:grep -oP 提取 + sort 排序 + uniq -c 计数,是日志分析的万能三件套。

场景八:校验 UUID / 版本号 / 语义化版本

// UUID v4
Pattern.compile(
    "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
    Pattern.CASE_INSENSITIVE);

// 语义化版本
Pattern.compile(
    "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)"
    + "(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)"
    + "(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"
    + "(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$");

// IP v4(带范围校验,不只是格式)
Pattern.compile(
    "^(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"
    + "\\.(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"
    + "\\.(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)"
    + "\\.(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$");

注意 IP 的正则:常见教程写的是 \\d{1,3} 三次,但那样 999.999.999.999 也会通过。上面的写法用 25[0-5]|2[0-4]\\d|[01]?\\d\\d? 精确限制了范围。

场景九:日志级别统计

# 按级别统计,一步到位
grep -oP '\b(ERROR|WARN|INFO|DEBUG|TRACE|FATAL)\b' app.log \
  | sort | uniq -c | sort -rn
# 按小时统计错误数(发现流量异常)
grep ' ERROR ' app.log \
  | grep -oP '^\d{4}-\d{2}-\d{2}T\d{2}' \
  | sort | uniq -c
// Java 侧高效计数:能用 Map 就别用多次正则扫描
Pattern LEVEL = Pattern.compile("\\b(ERROR|WARN|INFO|DEBUG|FATAL)\\b");
Map<String, AtomicLong> counter = new HashMap<>();

try (BufferedReader reader = Files.newBufferedReader(logPath)) {
    String line;
    Matcher m = LEVEL.matcher("");
    while ((line = reader.readLine()) != null) {
        m.reset(line);
        if (m.find()) {
            counter.computeIfAbsent(m.group(1), k -> new AtomicLong())
                   .incrementAndGet();
        }
    }
}

关键点:m.reset(line) 复用 Matcher 对象。每次 Pattern.matcher() 都会分配新对象,大文件下 GC 压力明显。

场景十:用正则做「行过滤」的加速

有个实测有效的技巧:先用 fast 过滤,再用正则精炼。

# ✗ 直接对 8G 文件跑正则,慢
grep -P 'ERROR.*Connection pool.*timeout' app.log | wc -l

# ✓ 先用简单字符串筛出候选行,再上正则
grep 'ERROR' app.log \
  | grep 'Connection pool' \
  | grep -c 'timeout'

实测(8G 日志):

方案                              耗时
单个复杂正则                        143s
先 grep 'ERROR' 再 grep 其余       22s   ← 快 6.5 倍
awk 单遍 + 字符串匹配                 11s   ← 最快

原理:正则引擎在每个位置都要尝试匹配,而 grep 的字面量查找用 Boyer-Moore 算法,跳过整块内存。先用便宜的筛选缩小候选集,再上昂贵的正则。

# awk 方案:单遍扫描 + 字符串查找
import sys
count = 0
for line in sys.stdin:
    if 'ERROR' in line and 'Connection pool' in line and 'timeout' in line:
        count += 1
print(count)
// Java 侧同理:先 contains 再正则
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
    if (line.contains("ERROR")
            && line.contains("Connection pool")
            && line.contains("timeout")) {
        Matcher m = FINE_PATTERN.matcher(line);
        if (m.find()) {
            count++;
        }
    }
}

性能对照表

操作                          8G 文件耗时
──────────────────────────────────────
grep 'ERROR'(字面量)              8s
grep -oP 'ERROR'                   14s
grep -oP '\bERROR\b'               19s
grep -P 'ERROR.*Connection.*timeout'  143s
awk 字符串多次 contains              11s
grep 'ERROR' | grep 'Connection'    22s

规律:

1. 字面量 < 带边界断言的单字符类 < 多元素正则
2. 限定前缀(如 'ERROR')能大幅缩小候选位置
3. 多次简单过滤 > 一次复杂匹配
4. 非捕获组 (?:) 比捕获组 () 更快
5. 大小写不敏感 (?i) 会变慢,能精确匹配就别用

自查清单

  • 有没有 (a+)+ 这类嵌套量词(ReDoS 风险)?
  • 复杂正则是否加了超时保护?
  • 是否有可以用 split/indexOf 替代的正则?
  • 日志脱敏是否覆盖了手机号/身份证/密钥/邮箱?
  • 脱敏正则是否加了边界断言(防止误伤长数字)?
  • 大文件分析是否用了「先字面量后正则」的分层过滤?
  • 复杂正则是否用 (?x) 模式加了注释?
  • 是否复用了 Matcher 对象(reset 而非重新 matcher)?
  • 多组捕获是否用了命名组而非数字索引?
  • 是否处理了 ANSI 转义符和 \r?

小结

  • 正则的三个性能坑:嵌套量词(ReDoS)、无前缀的宽泛匹配、逐行重新 matcher()
  • \K 和命名组能让正则可读性大幅提升
  • (?x) 模式让复杂正则像代码一样可维护
  • 分层过滤是最有效的优化:字面量筛候选 → 正则做精炼,实测快 6 倍
  • 脱敏必须加边界断言,否则会误伤订单号这类长数字
  • 不是所有字符串处理都该用正则 —— 先想想 split / indexOf / contains

这类排查技巧在之前的《慢查询日志分析》和《前端错误监控》里都用到了 —— 算法和工具是配套的。