常に数字で終わるURLがあります。例:
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
最後の2つのスラッシュ( "/")の間の数字を抽出したいと思います。
誰かが私がこれを行う方法を知っていますか?
常に数字で終わるURLがあります。例:
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
最後の2つのスラッシュ( "/")の間の数字を抽出したいと思います。
誰かが私がこれを行う方法を知っていますか?
文字列を分割できます:
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));
指定した入力の場合
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());
}
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 num = (num=url.substring(0, url.length() - 1)).substring(num.lastIndexOf('/')+1,num.length());