public virtual string Expand(IList<string> parms, IList<string> vals, ArticleDto activeArticle, IList<ArticleDto> allArticles) { IDictionary<string, string> vars = prepareVariables(parms, vals, activeArticle); Regex replaceRegex = new Regex(@"%([^\)%]+)%"); string expandedText = macroText; MatchCollection matches = replaceRegex.Matches(expandedText); Match[] matchArr = new Match[matches.Count]; matches.CopyTo(matchArr, 0); IEnumerable<Match> sortedMatches = (IEnumerable<Match>)matchArr.OrderByDescending(x => x.Index); foreach (Match match in sortedMatches) { string preText = expandedText.Substring(0, match.Index); string postText = expandedText.Substring(match.Index + match.Length); string parmName = match.Groups[1].Value; string value = ""; if (vars.ContainsKey(parmName)) value = vars[parmName]; expandedText = preText + value + postText; } return expandedText; }