Java 检查字符串末尾是否存在整数?

Java 检查字符串末尾是否存在整数?,java,Java,我想检查字符串末尾是否有一个数字,然后将这个数字(一个id)传递给我的函数。我现在意识到: String call = "/webapp/city/1"; String pathInfo = "/1"; if (call.equals("/webapp/city/*")) { //checking (doesn't work) String[] pathParts = pathInfo.split("/"); int id = pat

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

您可以使用检查字符串是否与给定模式匹配:

if (call.matches("/webapp/city/\\d+")) {
    ... //                      ^^^
        //                       |
        // One or more digits ---+
}
获得匹配项后,需要获取
拆分
的元素
[2]
,并使用以下方法将其解析为
int


为这项工作使用正确的工具:JAX-RS、SpringMVC、Restlet或任何REST框架。但是,您的代码没有意义:/webapp/city/*不可能等于/webapp/city/1。最后一个字符显然不一样。字符串数组包含字符串,所以它的第二个元素不可能是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
    }
}