Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading