在没有 MatchEvaluator 限制的情况下替换多个 Match

Replace multiple `Match`es without `MatchEvaluator`'s restrictions

我的应用程序在日期字符串中查找数字,例如 13/7/20197/13/2019

月份用 mm 代替,日子用 dd 代替。

如果只找到一个数字(例如6 July 2019),则应该假定它一定是日期。

如果不是,则 >12 的数字将是日期,另一个数字将是月份。

它使用 Regex.Matches(inputString, @"\d{1,2}")

查找数字

查看比赛后,我有 2 个变量 (Match? monthMatch, dayMatch)。

然后我制作字典:

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

问题是如何替换我拥有的 Dictionary<Match, string>

使用天真的方法,字符串中的索引在我第一次替换后发生了变化,第二次替换失败了。

例如。 7/13/2019 -> dd/13/2019 -> ddmm3/2019

我怎样才能确保根据原始字符串中的索引而不是中间替换进行替换。

我的解决方案是按索引的降序排列它们,这样 Match 对象的索引在每次替换后仍然有效。

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;
}