我的网址总是以数字结尾,例如:
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
我想提取最后两个斜杠之间的数字(“/").
有谁知道我怎么做到这一点?
答案 0 :(得分:8)
您可以拆分字符串:
String[] items = url.split("/");
String number = items[items.length-1]; //last item before the last slash
答案 1 :(得分:2)
使用正则表达式:
final Matcher m = Pattern.compile("/([^/]+)/$").matcher(url);
if (m.find()) System.out.println(m.group(1));
答案 2 :(得分: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的末尾找不到数字),但它将正常工作。
答案 3 :(得分: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());
}
答案 4 :(得分:1)
一线:
String num = (num=url.substring(0, url.length() - 1)).substring(num.lastIndexOf('/')+1,num.length());