问题描述
我有以下字符串作为全局规则:
I have following string as a glob rule:
**/*.txt
和测试数据:
/foo/bar.txt
/foo/buz.jpg
/foo/oof/text.txt
是否可以使用glob规则(不将glob转换为regex)匹配测试数据并返回有价值的条目?
Is it possible to use glob rule (without converting glob to regex) to match test data and return valud entries ?
一个要求:Java 1.6
推荐答案
如果您拥有Java 7,则可以使用 FileSystem.getPathMatcher
:
If you have Java 7 can use FileSystem.getPathMatcher
:
final PathMatcher matcher = FileSystem.getPathMatcher("glob:**/*.txt");
这需要将您的字符串转换为Path
的实例:
This will require converting your strings into instances of Path
:
final Path myPath = Paths.get("/foo/bar.txt");
对于Java的早期版本,您可能会从Apache Commons的 WildcardFileFilter
.您还可以尝试从Spring的 AntPathMatcher
-不过,这与从glob到正则表达式的方法非常接近.
For earlier versions of Java you might get some mileage out of Apache Commons' WildcardFileFilter
. You could also try and steal some code from Spring's AntPathMatcher
- that's very close to the glob-to-regex approach though.
这篇关于在Java中使用Glob匹配路径字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!