R – Add 10000 to numbers using Regex replace

regexvb.net

I need to replace some 2- and 3-digit numbers with the same number plus 10000. So

Photo.123.aspx

needs to become

Photo.10123.aspx

and also

Photo.12.aspx

needs to become

Photo.10012.aspx

I know that in .NET I can delegate the replacement to a function and just add 10000 to the number, but I'd rather stick to garden-variety RegEx if I can. Any ideas?

Best Solution

James is right that you want to use the Regex.Replace method that takes a MatchEvaluator argument. The match evaluator delegate is where you can take the numeric string you get in the match and convert it into a number that you can add 10,000 to. I used a lambda expression in place of the explicit delegate because its more compact and readable.

using System;
using System.Text.RegularExpressions;

namespace RenameAspxFile
{
    sealed class Program
    {
        private static readonly Regex _aspxFileNameRegex = new Regex(@"(\S+\.)(\d+)(\.aspx)", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
        private static readonly string[] _aspxFileNames= {"Photo.123.aspx", "Photo.456.aspx", "BigPhoto.789.aspx"};

        static void Main(string[] args)
        {
            Program program = new Program();
            program.Run();
        }

        void Run()
        {
            foreach (string aspxFileName in _aspxFileNames)
            {
                Console.WriteLine("Renamed '{0}' to '{1}'", aspxFileName, AddTenThousandToPhotoNumber(aspxFileName));
            }
        }

        string AddTenThousandToPhotoNumber(string aspxFileName)
        {
            return _aspxFileNameRegex.Replace(aspxFileName, match => String.Format("{0}{1}{2}", match.Result("$1"), Int32.Parse(match.Result("$2")) + 10000, match.Result("$3")));
        }
    }
}