假設id
的格式爲
可以使用正則表達式,遞增數解析它,然後重建。事情是這樣的:
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(\\D{4})(\\d{9})(\\D{4})");
final String input = "ABCD000000001XYZL";
final Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
final String head = matcher.group(1);
final long number = Long.parseLong(matcher.group(2)) + 1;
final String tail = matcher.group(3);
final String result = String.format("%s%09d%s", head, number, tail);
System.out.println(result);
}
}
您可以使用正則表達式snazzier和Matcher.appendReplacement
使代碼短一點;代價是複雜性:
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(?<=\\D{4})(\\d{9})(?=\\D{4})");
final String input = "ABCD000000001XYZL";
final Matcher matcher = pattern.matcher(input);
final StringBuffer result = new StringBuffer();
if (matcher.find()) {
final long number = Long.parseLong(matcher.group(1)) + 1;
matcher.appendReplacement(result, String.format("%09d", number));
}
matcher.appendTail(result);
System.out.println(result);
}
看看String.printf。或MessageFormat。 – bmargulies 2014-08-30 20:26:12
「ABCD」和「XYZL」總是相同的 - 你有硬編碼嗎? – 2014-08-30 20:31:23
是的這是硬編碼 – 2014-08-31 04:42:56