Get last set of numbers from string, do math, rebuild back into string?
.net-4.0, c#, regex
Solution
var src = "ap45245jpb1234h";
var match = Regex.Match(src, @"(?<=(\D|^))\d+(?=\D*$)");
if(match.Success)
{
var number = int.Parse(match.Value) + 1;
var newNum=string.Format(
"{0}{1}{2}",
src.Substring(0,match.Index),
number,
src.Substring(match.Index + match.Length));
newNum.Dump(); //ap45245jpb1235h
}
Explaining the regex: starting either from (the start of the string) or (a non-digit), match one or more digits that are followed by zero or more non-digits then the end of the string.
Of course, if the extracted number has leading zeros, things will go wrong. I'll leave this as an exercise to the reader.
Using a MatchEvaluator (as suggested by @LB in their answer) this becomes somewhat lighter:
Regex.Replace(
src,
@"(?<=(\D|^))\d+(?=\D*$)",
m => (int.Parse(m.Value)+1).ToString())
Problem
I have a field representing an "Account Number" that is anything but a number most of the time. I need to do some auto-incrementing of these "numbers". Clearly non-ideal for doing math with. The rule that we've decided works for us is that we want to find the right-most group of numbers and auto-increment them by one and return the rebuilt string (even if this makes it one character longer). Some examples of the numbers are: - AC1234 -> AC1235 - GS3R2C1234 -> GS3R2C1235 - 1234 -> 1235 - A-1234 -> A-1235 - AC1234g -> AC1235g - GS3R2C1234g -> GS3R2C1235g - 1234g -> 1235g - A-1234g -> A-1235g - 999 -> 1000 - GS3R2C9999g -> GS3R2C10000g I'm working with C#/.NET 4.0. I listed Regex as a tag but that isn't a requirement. This solution need not be in Regular Expressions. Any thoughts on a good way to do this? Ideal performance isn't a major concern. I'd rather have clear and easy-to-understand/maintain code for this unless it's all wrapped up in a Regex. Thanks!