2015-02-12 216 views
1

什麼是正則表達式從url中查找路徑參數?在url中使用正則表達式找到路徑參數

http://localhost:8080/domain/v1/809pA8 
https://localhost:8080/domain/v1/809pA8 

想要使用正則表達式從上述URL檢索值(809pA8),則優先使用java。

+1

你有什麼試過嗎?你看過基於簡單字符串函數的替代方法嗎? – reto 2015-02-12 08:46:32

+1

http://meta.stackoverflow.com/questions/285733 – GoBusto 2015-02-12 08:50:12

+1

user3157090,請閱讀[this](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – aioobe 2015-02-12 08:53:01

回答

4

我會建議你做這樣的事情

url.substring(url.lastIndexOf('/') + 1); 

如果你真的喜歡正則表達式,你可以做

Matcher m = Pattern.compile("/([^/]+)$").matcher(url); 

if (m.find()) 
    value = m.group(1); 
+0

更喜歡正則表達式。 – user3157090 2015-02-12 08:48:25

+1

爲什麼?這個問題對於需要正則表達式來說不夠複雜。 – GoBusto 2015-02-12 08:51:07

1

我會嘗試:

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

+0

這是錯誤的,因爲結束索引(subSequence的第二個參數)是獨佔的。該解決方案錯過了最後一個字符。 – aioobe 2015-02-12 09:14:33

+0

對不起,它的工作原理:https://ideone.com/E30ddC – Fourat 2015-02-12 09:29:39

+0

那麼,爲什麼使用'CharSequence.subSequence'而不是'String.substring'?對於'String.substring'結束索引是可選的(你不必使用'String.valueOf')。 – aioobe 2015-02-12 09:31:32