仅增加字母数字字符串中的数字

时间:2015-09-16 13:20:28

标签: java regex

我想增加一个字母数字字符串的数字。

示例1: ABC000DEF将是ABC001DEF

示例2: ABCDEF000将是ABCDEF001

它是根据字符串输入的格式递增的。

1 个答案:

答案 0 :(得分:1)

从字符串中提取数字然后递增并将其放回去,例如使用String.replaceXxx()Integer.parseInt()

如果您想增加多个独立数字,请尝试以下方法:

String input = "ABC999DEF999XYZ";

//find numbers
Pattern p = Pattern.compile( "[0-9]+" );    
Matcher m = p.matcher( input );   
StringBuffer sb = new StringBuffer();

//loop through all found groups
while( m.find() )
{
  //get the length of the current number
  int minLength = m.group().length();

  //parse the found number, increment and reformat it to the given min length
  String format = "%0"+minLength+"d";
  String incrementedNumber = String.format( format, Integer.parseInt( m.group() ) + 1 );

  //append the match and all text before to the StringBuffer
  m.appendReplacement( sb, incrementedNumber );
}

//append the rest of the input to the StringBuffer
m.appendTail( sb );

//prints ABC1000DEF1000XYZ
System.out.println( sb );