0

我有一个包含字符和数字的序列号,例如“ A1B2000C ”,我想通过增加数字部分+1来生成下一个序列号。下一个序列号将是A1B2001C。有什么办法可以存档吗?

4

4 回答 4

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");

但易读性受到影响

于 2012-11-23T02:41:09.610 回答
0

您必须知道序列号背后的逻辑:哪个部分意味着什么。增加哪个部分,哪个不增加。然后将数字分成组件,递增并构建新数字。

于 2012-11-23T02:40:31.090 回答
0

您可以使用如下正则表达式解析序列号:

([A-Z]\d+[A-Z])(\d+)([A-Z])$

此表达式创建的匹配为您提供 3 个组。第 2 组包含您要增加的数字。将其解析为一个整数,将其递增,然后通过将 group1 与新编号和 group3 连接起来来构建新的序列号。

于 2012-11-23T02:43:27.037 回答
0

您最好将序列号作为数字跟踪并连接您需要的任何前缀/后缀。

通过这种方式,您可以简单地增加序列号以生成下一个序列号,而不必费劲地刮掉最后一个生成的序列号。

public class Serials {
    int currentSerial = 2000;
    String prefix = "A1B";
    String suffix = "C";

    //Details omitted
    public String generateSerial() {
        return prefix + (currentSerial++) + suffix;
    }
}

请注意,如果必须保持数字的填充prefix="A1B2currentSerial=000事情会变得有点棘手,但是如果您搜索,有很多解决填充问题的方法:)

于 2012-11-23T02:45:06.947 回答