Example #1
0
        /// <summary>
        /// Replaces all occurrances of the given string with the replacement value using the specified formatting.
        /// </summary>
        /// <param name="toFind">The substring to find.</param>
        /// <param name="toReplace">The replacement value.</param>
        /// <param name="foregroundColor">The foreground color (defaults to the console's foreground color at initialization time).</param>
        /// <param name="backgroundColor">The background color (defaults to the console's background color at initialization time).</param>
        /// <returns>A new ConsoleString with the replacements.</returns>
        public ConsoleString Replace(string toFind, string toReplace, ConsoleColor?foregroundColor = null,
                                     ConsoleColor?backgroundColor = null)
        {
            ConsoleString ret = new ConsoleString();

            ret.Append(this);

            int startIndex = 0;

            while (true)
            {
                string toString     = ret.ToString();
                int    currentIndex = toString.IndexOf(toFind, startIndex);
                if (currentIndex < 0)
                {
                    break;
                }
                for (int i = 0; i < toFind.Length; i++)
                {
                    ret.RemoveAt(currentIndex);
                }
                ret.InsertRange(currentIndex,
                                toReplace.Select(c => new ConsoleCharacter(c, foregroundColor, backgroundColor)));
                startIndex = currentIndex + toReplace.Length;
            }

            return(ret);
        }
        /// <summary>
        /// Replaces all matches of the given regular expression with the replacement value using the specified formatting.
        /// </summary>
        /// <param name="regex">The regular expression to find.</param>
        /// <param name="toReplace">The replacement value.</param>
        /// <param name="foregroundColor">The foreground color (defaults to the console's foreground color at initialization time).</param>
        /// <param name="backgroundColor">The background color (defaults to the console's background color at initialization time).</param>
        /// <returns></returns>
        public ConsoleString ReplaceRegex(string regex, string toReplace, ConsoleColor?foregroundColor = null, ConsoleColor?backgroundColor = null)
        {
            ConsoleString ret = new ConsoleString();

            ret.Append(this);
            MatchCollection matches = Regex.Matches(this.ToString(), regex);

            foreach (Match match in matches)
            {
                ret = ret.Replace(match.Value, toReplace ?? match.Value, foregroundColor, backgroundColor);
            }

            return(ret);
        }