Tizz Tizz - 29 days ago 22
C# Question

Replacing ### with integers

By using RegEx, or String.Replace, I need to replace any number of consecutive #'s (with the appropriate number of leading 0's) with an integer. I know I can search for # in the string, get the First and Last index, Last-First for the length, then replace with String.Replace. I was hoping someone would have a faster, and more slick answer.

Method header would be:

string ReplaceHashtagsWithInt(string input, int integer)


Examples:

Input -> "String####_Hi##", 2

Output -> "String0002_Hi02"

Input -> "String####_Hi##", 123

Output -> "String0123_Hi123"

Answer
public static class Testing
{
    public static void Main()
    {
        ReplaceHashtagsWithInt("String####_Hi##", 2);
        ReplaceHashtagsWithInt("String####_Hi###", 123);
        ReplaceHashtagsWithInt("String####_Hi#######", 123);
    }

    public static string ReplaceHashtagsWithInt(string input, int integer)
    {
        Regex regex = new Regex("#+");

        var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();
        Array.Sort(matches);
        Array.Reverse(matches);

        foreach (string match in matches)
        {
            Regex r = new Regex(match);
            string zeroes = new string('0', match.Length - integer.ToString().Length) + integer;
            input = r.Replace(input, zeroes);
        }

        return input;
    }
}