-1

My application finds numbers in a date string for example 13/7/2019 or 7/13/2019.

It replaces them with mm for the month and dd for the day.

If only one number is found (eg. 6 July 2019), it should assume that it must be the day.

If not then the number that is >12 will be the day and the other one will be the month.

It find the numbers using Regex.Matches(inputString, @"\d{1,2}")

After looking through the matches, I have 2 variables (Match? monthMatch, dayMatch).

I then make a dictionary:

Dictionary<Match, string> matches = new();
if (monthMatch != null)
    matches.Add(monthMatch, "mm");
if (dayMatch != null)
    matches.Add(dayMath, "dd");

The question is how can I replace the Dictionary<Match, string> that I have.

Using the naive approach, the indexes in the string are changed after my first replacement and the second replacement fails miserably.

Eg. 7/13/2019 -> dd/13/2019 -> ddmm3/2019

How can I do this in a way that will ensure the replacements are made based on their index in the original string not an intermediate replacement.

trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
  • I have no idea what the motivation for closing this question was but it is not the same as the question it was marked as a duplicate of. – trinalbadger587 Aug 17 '21 at 22:57

1 Answers1

0

My solution was to order them in descending order of index so that the indexes of the Match objects would still be valid after each substitution.

public static string SafeSubstitution (string input, Dictionary<Match, string> substitutions)
{
    foreach (var (match, replaceWith) in substitutions.OrderByDescending(s => s.Key.Index))
    {
        string subResult = match.Result(replaceWith);
        input = string.Concat(input.Substring(0, match.Index), subResult, input.Substr(match.Index + match.Length));
    }
    return input;
}
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36