Tan
Tan

Reputation: 1585

grab last four digits approach after deleting non digits using regex

I'm getting the URL(http://localhost:8080/CompanyServices/api/creators/2173) shown below from a HTTP Response header and I want to get the id after the creators which is 2173.

So, I deleted all non digits as shown below and got the following result : 80802173. Is it a good approach to get the last 4 digits from the above set of digits?

One thing is that, this part localhost:8080 could change depending upon the server I deploy my application so I'm wondering if I should just grab something after creators/ ? If yes, then what is the best way to go about it?

public class GetLastFourIDs {


    public static void main(String args[]){  
        String str = "http://localhost:8080/CompanyServices/api/creators/2173";
        String replaceString=str.replaceAll("\\D+","");
        System.out.println(replaceString);  
        } 

}

Upvotes: 1

Views: 61

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79025

You can use regex API e.g.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "http://localhost:8080/CompanyServices/api/creators/2173";
        Pattern pattern = Pattern.compile("(creators/\\d+)");
        Matcher matcher = pattern.matcher(str);
        int value = 0;
        if (matcher.find()) {
            // Get e.g. `creators/2173` and split it on `/` then parse the second value to int
            value = Integer.parseInt(matcher.group().split("/")[1]);
        }
        System.out.println(value);
    }
}

Output:

2173

Non-regex solution:

public class Main {
    public static void main(String[] args) {
        String str = "http://localhost:8080/CompanyServices/api/creators/2173";
        int index = str.indexOf("creators/");
        int value = 0;
        if (index != -1) {
            value = Integer.parseInt(str.substring(index + "creators/".length()));
        }
        System.out.println(value);
    }
}

Output:

2173

[Update]

Incorporating comment by Andreas as follows:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "http://localhost:8080/CompanyServices/api/creators/2173";
        Pattern pattern = Pattern.compile("creators/(\\d+)");
        Matcher matcher = pattern.matcher(str);
        int value = 0;
        if (matcher.find()) {
            value = Integer.parseInt(matcher.group(1));
        }
        System.out.println(value);
    }
}

Output:

2173

Upvotes: 1

Related Questions