2012-06-25 117 views
4

我有網址,它總是一個數字結尾,例如:的Java:切片的String

String url = "localhost:8080/myproject/reader/add/1/"; 
    String anotherurl = "localhost:8080/myproject/actor/take/154/"; 

我想提取的最後兩條斜線之間的數字(「/」)。

有誰知道我該怎麼做?

回答

8

你可以分割字符串:

String[] items = url.split("/"); 
String number = items[items.length-1]; //last item before the last slash 
1

使用lastIndexOf,像這樣:

String url = "localhost:8080/myproject/actor/take/154/"; 
int start = url.lastIndexOf('/', url.length()-2); 
if (start != -1) { 
    String s = url.substring(start+1, url.length()-1); 
    int n = Integer.parseInt(s); 
    System.out.println(n); 
} 

這是基本的想法。您必須進行一些錯誤檢查(例如,如果在URL的末尾找不到數字),但它可以正常工作。

2

用正則表達式:

final Matcher m = Pattern.compile("/([^/]+)/$").matcher(url); 
if (m.find()) System.out.println(m.group(1)); 
1

對於您指定

String url = "localhost:8080/myproject/reader/add/1/"; 
String anotherurl = "localhost:8080/myproject/actor/take/154/"; 

加入少許的錯誤處理來處理失蹤 「/」 像

String url = "localhost:8080/myproject/reader/add/1"; 
String anotherurl = "localhost:8080/myproject/actor/take/154"; 

String number = ""; 
if(url.endsWith("/") { 
    String[] urlComps = url.split("/"); 
    number = urlComps[urlComps.length-1]; //last item before the last slash 
} else { 
    number = url.substring(url.lastIndexOf("/")+1, url.length()); 
} 
1

在其中輸入行:

String num = (num=url.substring(0, url.length() - 1)).substring(num.lastIndexOf('/')+1,num.length());