检查我的字符串末尾是否存在整数



我想检查我的字符串末尾是否存在一个数字,然后将这个数字(一个 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: Error :/webapp/city/1

您可以使用

matches(...) String方法来检查字符串是否与给定模式匹配:

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

获得匹配项后,您需要获取split的元素[2],并使用Integer.parseInt(...)方法将其解析为int

int id = Integer.parseInt(pathParts[2]);
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
    }
}

最新更新