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
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 usFRreplaceFirst("\\D+", ""): removes all non-digits from input, giving us000009
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));