下面的代码将根据 groupValues 集合进行匹配并构造替换字符串。此集合指定组索引和替换它的值的文本。
与其他解决方案不同,它不需要将整个匹配包含在组中,只需要包含您希望包含在组中的匹配部分。
public static string ReplaceGroups(Match match, Dictionary<int, string> groupValues)
{
StringBuilder result = new StringBuilder();
int currentIndex = 0;
int offset = 0;
foreach (KeyValuePair<int, string> replaceGroup in groupValues.OrderBy(x => x.Key))
{
Group group = match.Groups[replaceGroup.Key];
if (currentIndex < group.Index)
{
result.Append(match.Value.Substring(currentIndex, group.Index - match.Index - currentIndex));
}
result.Append(replaceGroup.Value);
offset += replaceGroup.Value.Length - group.Length;
currentIndex = group.Index - match.Index + group.Length;
}
return result.ToString();
}