Example #1
0
        private static Dictionary <string, Regex> CollectTemplateRegexes(TemplateReplacerBase replacerBase, Dictionary <string, TemplateReplacerBase> replacers)
        {
            // use the common format string provided by the base class of the family, not the inherited types
            var templatePatternFormat = replacerBase.TemplatePatternFormat ?? TEMPLATE_PATTERN_FORMAT;
            var regexes = new Dictionary <string, Regex>();

            // pin a precompiled Regex object for every template name handled by this replacer family
            foreach (var replacer in replacers)
            {
                // insert the replacer name (e.g. CurrentDate) into the regex
                var templatePattern = string.Format(templatePatternFormat, replacer.Key);

                // Create a _compiled_ regex. This forces .Net to cache a compiled (MSIL) version
                // of the regex so that it can be re-used whenever we need the same regex.
                // We have to work with Regex _instances_ instead of relying on the static API of
                // the Regex class (which is the recommended way) because the static API does not
                // contain the necessary overloads we need (a possibility to provide a start index
                // in the source text).
                // For details see the 'Compilation and Reuse in Regular Expressions' article.
                // https://msdn.microsoft.com/en-us/library/8zbs0h2f.aspx
                regexes.Add(replacer.Key, new Regex(templatePattern, RegexOptions.IgnoreCase | RegexOptions.Compiled));
            }

            return(regexes);
        }