← 中文资源

简体中文版本

PathMatcher 的 glob 与 regex 两种语法

getPathMatcher 的参数前缀决定语法:glob: 用 ** 跨目录匹配,regex: 直接接正则;同一个 matches 接口,两种写法各有适用面。

阅读英文原文

实现说明

活动部件是类 MatcherSyntaxes和函数 main。

使用要点

  • 每一步打印都带着自己的标签:glob log:、regex log:。

常见问题

运行「PathMatcher 的 glob 与 regex 两种语法」会打印什么?

运行文件本身,glob log:、regex log: 这些前缀各对应一段演示逻辑。

核心语句

PathMatcher glob = FileSystems.getDefault().getPathMatcher("glob:**/*.log");
.getPathMatcher("regex:.*app-\\d{4}-\\d{2}-\\d{2}\\.log");
Path log = Path.of("logs", "app-2026-11-22.log");

代码示例

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;

public class MatcherSyntaxes {

    public static void main(String[] args) {
        Path log = Path.of("logs", "app-2026-11-22.log");
        Path txt = Path.of("logs", "readme.txt");

        // glob 语法:** 跨目录段,* 只在单段内生效
        PathMatcher glob = FileSystems.getDefault().getPathMatcher("glob:**/*.log");

        // regex 语法:同一个接口直接接正则表达式
        PathMatcher regex = FileSystems.getDefault()
                .getPathMatcher("regex:.*app-\\d{4}-\\d{2}-\\d{2}\\.log");

        System.out.println("glob  log: " + glob.matches(log) + "  txt: " + glob.matches(txt));
        System.out.println("regex log: " + regex.matches(log) + "  txt: " + regex.matches(txt));
    }
}