Tries to parse number in the name brackets at the end of the value and then increment it to create a new name. Supports numbers at the end without brackets. The input name. Custom function to validate the created name. The new name.
(string name, Func<string, bool> isValid)
| 66 | /// <param name="isValid">Custom function to validate the created name.</param> |
| 67 | /// <returns>The new name.</returns> |
| 68 | public static string IncrementNameNumber(string name, Func<string, bool> isValid) |
| 69 | { |
| 70 | // Validate input name |
| 71 | if (isValid == null || isValid(name)) |
| 72 | return name; |
| 73 | |
| 74 | // Temporary data |
| 75 | int index; |
| 76 | int MaxChecks = 10000; |
| 77 | string result; |
| 78 | |
| 79 | // Find '<name><num>' case |
| 80 | var match = IncNameRegex1.Match(name); |
| 81 | if (match.Success && match.Groups.Count == 2) |
| 82 | { |
| 83 | // Get result |
| 84 | string num = match.Groups[0].Value; |
| 85 | |
| 86 | // Parse value |
| 87 | if (int.TryParse(num, out index)) |
| 88 | { |
| 89 | // Get prefix |
| 90 | string prefix = name.Substring(0, name.Length - num.Length); |
| 91 | |
| 92 | // Generate name |
| 93 | do |
| 94 | { |
| 95 | result = string.Format("{0}{1}", prefix, ++index); |
| 96 | |
| 97 | if (MaxChecks-- < 0) |
| 98 | return name + Guid.NewGuid(); |
| 99 | } while (!isValid(result)); |
| 100 | |
| 101 | if (result.Length > 0) |
| 102 | return result; |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | // Find '<name> (<num>)' case |
| 107 | match = IncNameRegex2.Match(name); |
| 108 | if (match.Success && match.Groups.Count == 2) |
| 109 | { |
| 110 | // Get result |
| 111 | string num = match.Groups[0].Value; |
| 112 | num = num.Substring(1, num.Length - 2); |
| 113 | |
| 114 | // Parse value |
| 115 | if (int.TryParse(num, out index)) |
| 116 | { |
| 117 | // Get prefix |
| 118 | string prefix = name.Substring(0, name.Length - num.Length - 2); |
| 119 | |
| 120 | // Generate name |
| 121 | do |
| 122 | { |
| 123 | result = string.Format("{0}({1})", prefix, ++index); |
| 124 | |
| 125 | if (MaxChecks-- < 0) |