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).
CodePudding user response:
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 usFR
replaceFirst("\\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));
CodePudding user response:
Why not just split between digits and leters:
String input = "FR100109";
String[] splited = input.split("(?<=\\D)(?=\\d)");
int incremented = Integer.parseInt(splited[1]) 1;
String formated = String.format("%0" splited[1].length() "d", incremented);
System.out.println(splited[0] formated);
CodePudding user response:
You need a method where you can pass in the country code and create a new string from the old one.
Your requirement isn't clear. I can't tell if you always want to increment the value, regardless of country code.
I think you need a better abstraction than a String. I don't know what this String is, but I'd recommend a class with a static counter and a method that takes in a country code and returns a String value after incrementing the counter. No parsing needed.