Globs are not regular expression. Glob is simpler and earlier than regular expression. For historical reasons, glob are more used as file name or file path filtering.
In Java 7 NIO package has 2 places that glob appears as file names or file path filter. One is when you create a PathMatcher to test if a java.nio.file.Path instance matches a patten like
Path path = Paths.get("abc.java");
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.java");
boolean isJavaFile = matcher.matches(path); // true
The other is when create a DirectoryStream to iterate all files and subdirectories( not including files under subdirectories, just like the command 'dir' or 'ls')
Path dir = Paths.get("/tmp");
try (DirectoryStream<path> stream = Files.newDirectoryStream(dir,"[vt]*")) {
for (Path path : stream) {
System.out.println(path.getFileName()); // only files start with 'v' or 't'
}
}
Here are the rules for glob:
- * match any char except a directory boundary
- ** match any char include a directory boundary
- ? match any ONE char
- [] same as regular express, like [0-9] match any ONE digit.
- {} match a collection of patten separated by comma ','. Such as {A*, b} means either a string start with 'A' or a single char 'b'.
More examples:
path | glob | math result |
/tmp/src/main/Demo.java | *.java | false |
/tmp/src/main/Demo.java | **.java | true |
/tmp/src/main/Demo.java | /tmp/*/*.java | false |
/tmp/src/main/Demo.java | /tmp/**/*.java | true |
/tmp/src/main/Demo.java | /tmp/**/[dD]*.java | true |
/tmp/src/main/Demo.java | /tmp/**/[aA]*.java | false |
0 comments:
Post a Comment