我有以下字符串作为通配符规则:
**/*.txt
并测试数据:
/foo/bar.txt
/foo/buz.jpg
/foo/oof/text.txt
是否可以使用glob规则(而不是将glob转换为正则表达式)来匹配测试数据并返回有效条目?
一个要求:Java 1.6
FileSystem.getPathMatcher
:final PathMatcher matcher = FileSystem.getPathMatcher("glob:**/*.txt");
Path
实例:final Path myPath = Paths.get("/foo/bar.txt");
WildcardFileFilter
。你也可以从Spring的AntPathMatcher
中借鉴一些代码-虽然这非常接近于glob-to-regex方法。FileSystem#getPathMatcher(String)
是一个抽象方法,你不能直接使用它。你需要先获得一个 FileSystem 实例,例如默认实例:
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
// file path
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
m.matches(Paths.get("/foo/bar.txt")); // true
m.matches(Paths.get("/foo/bar.txt").getFileName()); // false
// file name only
PathMatcher n = FileSystems.getDefault().getPathMatcher("glob:*.txt");
n.matches(Paths.get("/foo/bar.txt")); // false
n.matches(Paths.get("/foo/bar.txt").getFileName()); // true
补充之前的回答:使用来自Apache commons-lang
库的org.apache.commons.io.FilenameUtils.wildcardMatch(filename, wildcardMatcher)
函数。
FileSystem.getPathMatcher
进行修改,以适应你的需求。 - Boris the Spider