PathMatcher Glob And Regex Syntax

One getPathMatcher call serves both syntaxes: glob: patterns cross directories with ** while regex: matches paths with a plain regular expression.

JavaCli Tooling

Code

snippet
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));
    }
}

What happens on each run — PathMatcher Glob And Regex Syntax

The moving parts are the class MatcherSyntaxes and the function main.

What to watch for

  • The toolchain by itself suffices; no dependency resolution ever runs.

Using it

The declaration that drives everything: public static void main(String[] args)

Output lines are prefixed (glob log:, regex log:), so every label can be traced to its producing step.

Key statements

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");

Interactive Tools for This Topic

FAQ

What does PathMatcher Glob And Regex Syntax print when run?
Invoke the file as-is — the `glob log:`, `regex log:` prefixes identify which step printed each line.