2016-12-06 32 views
1

我需要在java中进行一些基本的url匹配。我需要将返回true的方法,说用于检查URL是否适合模式的Java方法

/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

好像你可能想要一个蚂蚁匹配器;有这样的库可用。 – chrylis

+0

'users/5/6/7/roles'应该返回什么? [String.matches()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String))需要一个正则表达式,'/用户/ [0-9] + /角色“应该可以工作。 –

+0

@JohnBupit false – JellyRaptor

回答

1

一种方式是通过某种形式的正则表达式等同物如[^/]+来代替*,但是那种这里所使用的模式实际上被称为“水珠”的格局。从Java 7开始,您可以使用FileSystem.getPathMatcher来针对全局模式匹配文件路径。有关glob语法的完整说明,请参阅getPathMatcher的文档。

public boolean fitsTemplate(String path, String template) { 
    return FileSystems.getDefault() 
         .getPathMatcher("glob:" + template) 
         .matches(Paths.get(path)); 
} 
+0

是的,这是完美的。我记得术语“glob”引用了从我接触到像Gulp这样的Javascript任务跑步者的URL /路径匹配。它一直使用球体来传达一个模式来匹配。 – JellyRaptor

相关问题