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