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

Increment the number part of a String but keeping the character part in Java

I came across several questions but without an answer for my problem.

I have a code camming from data-base in this format: FR000009.

The output should be: FR000010

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

String original = "FR000009";
    String incremented = "FR" +  String.format("%0" + (original.length() - 2) + "d",
            Integer.parseInt(original.substring(2)) + 1);
    System.out.println(incremented);

Here came the difference from other questions: I want to parse the string without the need of hardcoding FR like in the example above. In time there can be different country codes (DE, UK,RO etc).

>Solution :

You can use this code by stripping all digits first and then stripping all non-digits:

String original = "FR000009";

String repl = String.format("%s%0" + (original.length() - 2) + "d",
    original.replaceFirst("\\d+", ""),
   (Integer.valueOf(original.replaceFirst("\\D+", "")) + 1));
//=> "FR000010"

Here:

  • replaceFirst("\\d+", ""): removes all digits from input, giving us FR
  • replaceFirst("\\D+", ""): removes all non-digits from input, giving us 000009

Note that if there are always only 2 letters at the start and remaining are digits then you won’t even need a regex code, just use substring:

String repl = String.format("%s%0" + (original.length() - 2) + "d",
   original.substring(0, 2),
   (Integer.valueOf(original.substring(2)) + 1));
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