简体   繁体   English

获取String的最后一个数字部分

[英]get last number part of a String

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. 我有一个序列号不包含字符和数字,类似' A1B2000C ',我想通过增加数字部分+1来生成下一个序列号。 The next serial no will be A1B2001C . 下一个序列号将是A1B2001C Is there any way to archieve it? 有没有办法实现它?

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 但易读性受到影响

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. 然后将数字分成组件,增加并构建新数字。

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. 此表达式创建的匹配为您提供3组。 Group 2 contains the number you want to increment. 第2组包含要增加的数字。 Parse it into an integer, increment it and then build the new serial number by concatenating group1 with the new number and group3. 将其解析为整数,递增它,然后通过将group1与新数字和group3连接来构建新的序列号。

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 :) 请注意,如果prefix="A1B2currentSerial=000那么必须维护数字的填充变得有点棘手,但是如果你搜索,有很多解决填充问题的方法:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM