在Java中使用Glob匹配路径字符串 [英] Match path string using glob in Java

查看:370
本文介绍了在Java中使用Glob匹配路径字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串作为全局规则:

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,则可以使用

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的

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匹配路径字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆