public string Substitute(string subject, string regex, string replace, RegexOption option = DefaultOption, int offset = 0)
{
// Special cases, if $N is passed then use the substring as the replacement
// if #N is passed then use substring, pad with a space on either side
var group = -1;
var substituteGroup = replace.Length == 2 && (replace[0] == '$' || replace[0] == '#') &&
int.TryParse(replace[1].ToString(), out group);
var pad = !substituteGroup ? false : replace[0] == '#';
var r = new Regex(regex, option);
var match = r.Execute(subject);
var replacements = new List<Replacement>();
while (match.Success)
{
if (match.Groups[0].Start >= offset)
{
var doReplace = false;
if (substituteGroup)
{
if (match.Groups.Count > group)
{
doReplace = true;
replace = string.Format("{0}{1}{0}", pad ? " " : "", match.Groups[group].Value);
}
}
else
{
doReplace = true;
}
if (doReplace)
{
replacements.Add(new Replacement
{
Start = match.Groups[0].Start,
Length = match.Groups[0].Length,
Value = replace
});
}
}
match = match.NextMatch;
}
replacements.Reverse();
foreach (var replacement in replacements)
{
subject = subject.Remove(replacement.Start, replacement.Length);
subject = subject.Insert(replacement.Start, replacement.Value);
}
return subject;
}