2016-12-06 58 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

相關問題