什麼是正則表達式從url中查找路徑參數?在url中使用正則表達式找到路徑參數
http://localhost:8080/domain/v1/809pA8
https://localhost:8080/domain/v1/809pA8
想要使用正則表達式從上述URL檢索值(809pA8),則優先使用java。
什麼是正則表達式從url中查找路徑參數?在url中使用正則表達式找到路徑參數
http://localhost:8080/domain/v1/809pA8
https://localhost:8080/domain/v1/809pA8
想要使用正則表達式從上述URL檢索值(809pA8),則優先使用java。
我會建議你做這樣的事情
url.substring(url.lastIndexOf('/') + 1);
如果你真的喜歡正則表達式,你可以做
Matcher m = Pattern.compile("/([^/]+)$").matcher(url);
if (m.find())
value = m.group(1);
更喜歡正則表達式。 – user3157090 2015-02-12 08:48:25
爲什麼?這個問題對於需要正則表達式來說不夠複雜。 – GoBusto 2015-02-12 08:51:07
我會嘗試:
String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/'), url.length()-1));
無需正則表達式,我想。
編輯:對不起,我犯了一個錯誤:
String url = "http://localhost:8080/domain/v1/809pA8";
String value = String.valueOf(url.subSequence(url.lastIndexOf('/')+1, url.length()));
看到這個代碼在這裏工作:https://ideone.com/E30ddC
爲您簡單的情況下,正則表達式是矯枉過正,爲他人注意。但是,如果你有更多的案例,這就是爲什麼你更喜歡正則表達式,如果你使用Spring,給Spring看一下AntPathMatcher#extractUriTemplateVariables。它實際上比直接使用正則表達式更適合提取路徑變量。 Here are some good examples。
你有什麼試過嗎?你看過基於簡單字符串函數的替代方法嗎? – reto 2015-02-12 08:46:32
http://meta.stackoverflow.com/questions/285733 – GoBusto 2015-02-12 08:50:12
user3157090,請閱讀[this](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – aioobe 2015-02-12 08:53:01