Example of all the regular special character methods in an c escape string

  • 2020-05-30 20:56:52
  • OfStack


/// <summary>
        ///  Escapes all regular special characters in a string 
        /// </summary>
        /// <param name="input"> Incoming string </param>
        /// <returns></returns>
        string FilterString(string input)
        {
            input = input.Replace("\\", "\\\\");// To replace" \ "Or else there will be other ones because of the substitution." \ " 
            Regex r = new Regex("[\\*\\.\\?\\+\\$\\^\\[\\]\\(\\)\\{\\}\\|\\/]");
            MatchCollection ms = r.Matches(input);
            List<string> list = new List<string>();
            foreach (Match item in ms)
            {
                if (list.Contains(item.Value))
                    continue;
                input = input.Replace(item.Value, "\\" + item.Value);
                list.Add(item.Value);
            }
            return input;
        }


Related articles: