嘗試正則表達式提取的最後一個數字(我們有遞增):
private static string Next(string value) {
string number = Regex.Match(value, "[0-9]+$").Value;
return value.Substring(0, value.Length - number.Length) +
(long.Parse(number) + 1).ToString().PadLeft(number.Length, '0');
}
或者Regex.Replace
版本,這是更簡潔,但不可讀:
private static string Next(string value) {
return Regex.Replace(value, "[0-9]+$",
match => (long.Parse(match.Value) + 1).ToString($"D{match.Length}"));
}
測試:
// "abc0046"
Console.Write(Next("abc0045"));
// "abc0045xyz124" (please, notice, that it's the last 123 which is incremented)
Console.Write(Next("abc0045xyz123"));
如果你有一個項目與相同的模式一個序列可以使用的Linq:
string[] items = new string[] { "ABC001", "ABC105", "ABC024" };
// "ABC106"
Console.Write(Next(items.Max()));
請出示你嘗試過什麼,什麼是不與它 –