原创

Java-生产新的唯一字符串-字符串追加序号

public static void main(String[] args) {
String oldTrainName00 = "t-est";
System.out.println(getUniqueIndexTrainName(oldTrainName00));
String oldTrainName0 = "-test";
System.out.println(getUniqueIndexTrainName(oldTrainName0));
String oldTrainName1 = "test";
System.out.println(getUniqueIndexTrainName(oldTrainName1));
String oldTrainName2 = "test-";
System.out.println(getUniqueIndexTrainName(oldTrainName2));
String oldTrainName3 = "test-1";
System.out.println(getUniqueIndexTrainName(oldTrainName3));
String oldTrainName4 = "test-11";
System.out.println(getUniqueIndexTrainName(oldTrainName4));

// t-est-1
// -test-1
// test-1
// test-1
// test-2
// test-12
}

private static String getUniqueIndexTrainName(String oldTrainName) {

// 如果是 - 或者 -数字 结尾
//(([1-9][0-9]{0,})?) 可选
Pattern p = Pattern.compile("^(.*?)-(([1-9][0-9]{0,})?)$");
Matcher m = p.matcher(oldTrainName);
if (m.matches()) {
int index = oldTrainName.lastIndexOf("-");
if (index < 0) {
return oldTrainName + "-1";
}
String prefix = oldTrainName.substring(0, index);
String subfix = oldTrainName.substring(index + 1);
try {
int start = Integer.valueOf(subfix);
return prefix + "-" + (start + 1);
} catch (Exception ignore) {
return prefix + "-1";
}
} else {
return oldTrainName + "-1";
}
}
正文到此结束
本文目录