How to extract the instance value in the string efficently

I have a string "/p4products/nemis2/filehandlerU/encdv2/work/10098325" which is coming as input from CMD.
In this string the "encdv" is the environment name and "2" is the instance ID. Environment name can be either "encdv1","encdv2","encpr1","encpr2" and so on but Instance ID can be "1" or "2" only. I want to extract the instance ID whenever I encounter this string.

I thought to use indexOf and then finally charAt to get the value and that is working fine. But is there any way that is more convenient than this as this approach seems to have flaws if the string gets changed in future.

My Code Snippet:

public static void main(String[] args) {
    String s = "/p4products/nemis2/filehandlerU/encdv2/work/10098325";
    int instId = s.indexOf("enc");
    int instIdVerify = s.indexOf("/work");
    if (instId  + 5 == instIdVerify -1)
    System.out.println(s.charAt(instId + 5));

>Solution :

We can use String#replaceAll for a one-liner solution:

String input =  "/p4products/nemis2/filehandlerU/encdv2/work/10098325";
String envNum = input.replaceAll(".*/enc(?:dv|pr)(\\d+)/.*", "$1");
System.out.println(envNum);  // 2

Leave a Reply