Reputation: 35
I have a serial no contain both characters and numbers, something like 'A1B2000C', I want to generate next serial no by increasing number part +1. The next serial no will be A1B2001C. Is there any way to archieve it?
Upvotes: 0
Views: 3585
Reputation: 425398
Not in one line, but...
String input = "A1B2000C";
String number = input.replaceAll(".*(?<=\\D)(\\d+)\\D*", "$1");
int next = Integer.parseInt(number);
next++;
String ouput = input.replaceAll("(.*)(?<=\\D)\\d+(\\D*)", "$1" + next + "$2");
System.out.println(ouput);
output:
A1B2001C
Actually, it can be done in one line!
String ouput = input.replaceAll("(.*)\\d+(\\D*)", "$1" + (Integer.parseInt(input.replaceAll(".*(\\d+)\\D*", "$1") + 1) "$2");
But legibility suffers
Upvotes: 2
Reputation: 1149
You would be better off keeping track of the serial number as a number and concatenating whatever prefixes/suffixes you need.
This way you can simply increment the serial number to generate the next one rather than having to faff-about with scraping the last serial generated.
public class Serials {
int currentSerial = 2000;
String prefix = "A1B";
String suffix = "C";
//Details omitted
public String generateSerial() {
return prefix + (currentSerial++) + suffix;
}
}
Note that if prefix="A1B2
and currentSerial=000
then things get a little trickier with having to maintain the padding of the number, but there are many solutions to the padding issue around if you search :)
Upvotes: 0
Reputation: 3675
You can parse the serial number with a regular expression like this one:
([A-Z]\d+[A-Z])(\d+)([A-Z])$
The match created by this expression gives you 3 groups. Group 2 contains the number you want to increment. Parse it into an integer, increment it and then build the new serial number by concatenating group1 with the new number and group3.
Upvotes: 0
Reputation: 28767
You have to know the logic behind the serial number: which part means what. Which part to increment, which not. Then you separate the number into components, increment and build the new number.
Upvotes: 0