我有一个序列号不包含字符和数字,类似于“ A1B2000C ”,我想通过增加第+1部分来生成下一个序列号。下一个序列号为 A1B2001C 。有没有办法实现它呢?
答案 0 :(得分:2)
不是一行,而是......
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);
输出:
A1B2001C
实际上,它可以在一行中完成!
String ouput = input.replaceAll("(.*)\\d+(\\D*)", "$1" + (Integer.parseInt(input.replaceAll(".*(\\d+)\\D*", "$1") + 1) "$2");
但易读性受到影响
答案 1 :(得分:0)
你必须知道序列号背后的逻辑:哪一部分意味着什么。哪个部分要增加,哪个不增加。 然后将数字分成组件,增加并构建新数字。
答案 2 :(得分:0)
您可以使用正则表达式解析序列号,如下所示:
([A-Z]\d+[A-Z])(\d+)([A-Z])$
此表达式创建的匹配为您提供3组。第2组包含要增加的数字。将其解析为整数,递增它,然后通过将group1与新数字和group3连接来构建新的序列号。
答案 3 :(得分:0)
最好将序列号跟踪为数字并连接所需的前缀/后缀。
通过这种方式,您可以简单地增加序列号以生成下一个序列号,而不必通过抓取最后生成的序列进行操作。
public class Serials {
int currentSerial = 2000;
String prefix = "A1B";
String suffix = "C";
//Details omitted
public String generateSerial() {
return prefix + (currentSerial++) + suffix;
}
}
请注意,如果prefix="A1B2
和currentSerial=000
,那么必须维护数字的填充变得有点棘手,但是如果搜索,有很多解决填充问题的方法:)