Paul
Paul

Reputation: 362

Check if a integer is present at the end of my string?

I would like to check if a number is present at the end of my string, to then pass this number (an id) to my function. Here is what I realized for the moment:

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 (...)

Error :

java.lang.RuntimeException: Error : /webapp/city/1

Upvotes: 1

Views: 125

Answers (2)

Melron
Melron

Reputation: 579

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
    }
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You can use matches(...) method of String to check if your string matches a given pattern:

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

Once you get a match, you need to get element [2] of the split, and parse it into an int using Integer.parseInt(...) method:

int id = Integer.parseInt(pathParts[2]);

Upvotes: 2

Related Questions