Java PathMatcher pattern

Introduction

The value for PathMatcher pattern:

syntax:pattern

The value for syntax is either glob or regex.

The glob pattern uses the following syntax rules:

Pattern
Rule
*
match zero or more characters without crossing directory boundaries.

match zero or more characters crossing directory boundaries.
?
matches exactly one character.
\
escape character. \\ matches a single backslash, and \* matches an asterisk.
[]



matches a single character. For example,
[aeiou] matches a, e, i, o, or u.
[a-z] matches all alphabets between a and z.
! after the left bracket is negation. [!cat] matches all characters except c, a, t.
{}
matches groups, for example, {txt, java, doc} matches txt, java, and doc.
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    String globPattern = "glob:**txt";
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher(globPattern);
    Path path = Paths.get("Main.txt");
    boolean matched = matcher.matches(path);
    System.out.format("%s matches %s: %b%n", globPattern, path, matched);
  }/* w w w . ja v  a2 s . c  o m*/
}



PreviousNext

Related