string[] src = { "AC1234", "GS3R2C1234", "1234", "A-1234", "AC1234g", "GS3R2C1234g", "1234g", "A-1234g", "999", "GS3R2C9999g" }; foreach (string before in src) { string after = Regex.Replace(before, @"\d+(?=\D*$)", m => (Convert.ToInt64(m.Value) + 1).ToString()); Console.WriteLine("{0} -> {1}", before, after); }
exit:
AC1234 -> AC1235 GS3R2C1234 -> GS3R2C1235 1234 -> 1235 A-1234 -> A-1235 AC1234g -> AC1235g GS3R2C1234g -> GS3R2C1235g 1234g -> 1235g A-1234g -> A-1235g 999 -> 1000 GS3R2C9999g -> GS3R2C10000g
notes:
@LB using lambda expressions like MatchEvaluator FTW!
From @spender's answer, lookahead - (?=\D*$) - ensures that only the last group of digits matches (but lookbehind - (?<=(\D|^)) is not required).
The RightToLeft parameter used by @JeffMoser allows it to first match the last group of numbers, but there is no static Replace method that allows you to (1) specify RegexOptions, (2) use a MatchEvaluator, and (3) limit the number of replacements. You must first create an instance of the Regex object:
string[] src = { "AC1234", "GS3R2C1234", "1234", "A-1234", "AC1234g", "GS3R2C1234g", "1234g", "A-1234g", "999", "GS3R2C9999g" }; foreach (string before in src) { Regex r = new Regex(@"\d+", RegexOptions.RightToLeft); string after = r.Replace(before, m => (Convert.ToInt64(m.Value) + 1).ToString(), 1); Console.WriteLine("{0} -> {1}", before, after); }
exit:
AC1234 -> AC1235 GS3R2C1234 -> GS3R2C1235 1234 -> 1235 A-1234 -> A-1235 AC1234g -> AC1235g GS3R2C1234g -> GS3R2C1235g 1234g -> 1235g A-1234g -> A-1235g 999 -> 1000 GS3R2C9999g -> GS3R2C10000g
Alan moore
source share