我需要在java中进行一些原始的url匹配。我需要一个返回true的方法,说
/users/5/roles
匹配
/users/*/roles
这是我正在寻找的和我尝试过的。
public Boolean fitsTemplate(String path, String template) {
Boolean matches = false;
//My broken code, since it returns false and I need true
matches = path.matches(template);
return matches;
}
答案 0 :(得分:1)
一种选择是将*
替换为某种类型的正则表达式,例如[^/]+
,但这里使用的模式实际上称为" glob"图案。从Java 7开始,您可以使用FileSystem.getPathMatcher
来匹配glob模式的文件路径。有关glob语法的完整说明,请参阅getPathMatcher
的文档。
public boolean fitsTemplate(String path, String template) {
return FileSystems.getDefault()
.getPathMatcher("glob:" + template)
.matches(Paths.get(path));
}