Is it possible to write this code fragment more compactly or not?

string newString = oldString.Replace(" ","") .Replace(" ", "") .Replace("-", "") .Replace(".", "") .Replace(",", "") .Replace("(", "") .Replace(")", "") .Replace("{", "") .Replace("}", "") .Replace("[", "") .Replace("]", "") .Replace("!", "") .Replace("@", "") .Replace("#", "") .Replace("$", "") .Replace("%", "") .Replace("^", "") .Replace("*", "") .Replace("+", "") .Replace("=", "") .Replace(":", "") .Replace(";", "") .Replace("/", "") .Replace(@"\", ""); 

    3 answers 3

    You can use Regex.Replace - in the specified input line replaces all the lines that match the regular expression pattern specified by the replacement string.

      string input = "This @#$[ываыв] %is text with some test data %$ dsffs !@#$%"; string pattern = "[-.,(){}@#$%^&*!+=:;/\\[\\]]+"; string replacement = ""; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); // This @#$[ываыв] %is text with some test data %$ dsffs !@#$% Console.WriteLine("Original String: {0}", input); // This ываыв is text with some test data dsffs Console.WriteLine("Replacement String: {0}", result); 

    http://ideone.com/CVYgJG

    I am not an expert on regulars, but as an example, I think this will help find the right path.

    • Thanks to all! But I made it even shorter string newString = Regex.Replace (oldString, "[-., () {} @ # $% ^ <>? & *! + =:; / \ [\]] +", "") ; - ArtemiyMVC
    • @ArtemiyMVC I specifically divided, so that it was clear that where it comes from. But you, of course, have the right to do everything as you please) The main regular plan is to make up correctly - Alexey Shimansky

    As you advised above, use the regular service. The problem of your code is not only in its verbosity and duplication, but also in the fact that every time you call Replace, the string is re-created (due to the immutability of the strings in C #). Therefore, if the lines are large enough and / or this code will be called many times, you risk getting a substantial overhead to repeatedly re-create your line. I am not going to judge what is happening there in the depths of Regex.Replace , but surely its algorithm approaches this issue much more economically than a multiple call to Replace with the re-creation of a string.

    • Yes, Regex.Replace internally uses StringBuilder . - andreycha

    If the number of calls and / or row sizes are large enough, then I recommend the following method, which significantly (several times) wins the rate of fire of Regex :

     private static string ClearString(string s) { StringBuilder sb = new StringBuilder(s.Length); foreach (char c in s) { switch (c) { case ' ': case '\t': case '-': case '+': case '=': case '.': case ',': case ':': case ';': case '(': case ')': case '{': case '}': case '[': case ']': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '\\': case '/': break; default: sb.Append(c); break; } } return sb.ToString(); } 

    Here, of course, it does not smell like compactness, but the efficiency is decent.

    • I would give examples of numbers for completeness. (Although the author, in my opinion, is concerned exclusively with the compactness of the code.) - andreycha
    • @andreycha Yes, I am happy. It runs about 5 times faster than a precompiled Regex . - Dmitry D.