2017-11-11 3 views
3

文字列の最後に数字があるかどうかをチェックして、この番号(ID)を関数に渡したいと思います。ここで私は一瞬のために実現するものである:文字列の最後に整数があるかどうかを確認しますか?

String call = "/webapp/city/1"; 
String pathInfo = "/1"; 


    if (call.equals("/webapp/city/*")) { //checking (doesn't work) 
      String[] pathParts = pathInfo.split("/"); 
      int id = pathParts[1]; //desired result : 1 
      (...) 
    } else if (...) 

エラー:

java.lang.RuntimeException:エラー:/ webappの/都市/ 1

+0

は仕事のための適切なツールを使用します:JAX-RS、春MVC、のRestlet、または任意のREST OUはsplitの要素[2]を取得し、Integer.parseInt(...)方法を使用してintにそれを解析する必要がありますフレームワーク。しかし、まあ、あなたのコードは意味をなさない:/ webapp/city/*できない**平等**/webapp/city/1。最後の文字は明らかに同じではありません。 String配列にはStringが含まれているため、2番目のeementはintである可能性がありません。 –

答えて

2

あなたがチェックするためにmatches(...) method of Stringを使用することができますあなたの文字列が指定されたパターンと一致する場合:

if (call.matches("/webapp/city/\\d+")) { 
    ... //      ^^^ 
     //      | 
     // One or more digits ---+ 
} 

一致すると、y

int id = Integer.parseInt(pathParts[2]); 
1
final String call = "http://localhost:8080/webapp/city/1"; 
int num = -1; //define as -1 

final String[] split = call.split("/"); //split the line 
if (split.length > 5 && split[5] != null) //check if the last element exists 
    num = tryParse(split[5]); // try to parse it 
System.out.println(num); 

private static int tryParse(String num) 
{ 
    try 
    { 
     return Integer.parseInt(num); //in case the character is integer return it 
    } 
    catch (NumberFormatException e) 
    { 
     return -1; //else return -1 
    } 
} 
関連する問題