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.
Code
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
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.